首页 > 解决方案 > 为什么在构造函数中将字符串分配给指针是安全的?

问题描述

我有一堂课:.h

class test {
public:
    int Length;
    char* Name;
    int* ARR;
    test(int l, char* n, int* a);
    test();
};

.cpp

test::test(int l, char* n, int* a){
    Length=l;
    Name=n;
    ARR=a;
}

和 main.cpp

#include<iostream>
void InAFunc(test *kio) {
    int foo[3] = { 1,2,3 };
    *kio = test(7, "Hello!", foo);
}
int main() {
    test mmk;
    InAFunc(&mmk);
    std::cout << mmk.Name << mmk.ARR[1];
}

据我所知,我可能会在 ARR 上遇到异常,因为变量 foo 已在函数 InAFunc 的末尾释放。我需要对 Arr 执行 new 或 malloc 以避免它。我的问题是为什么“你好!” 是安全的?我过去写过很多这样的代码,但从来没有错。为什么在没有 new 或 malloc 的构造函数中留下一个字符串是可以的?这个类中的变量名是一个指针。

标签: c++constructor

解决方案


字符串“Hello”是在string literal整个程序期间都存在的。因此,您始终可以在不破坏指针的情况下指向它。它不会在函数结束时被销毁。


推荐阅读