简体   繁体   English

C++指针成员初始化

[英]C++ pointer member initialization

I know this is really basic, but I don't know the answer given my very limited C++ usage.我知道这真的很基础,但鉴于我的 C++ 使用非常有限,我不知道答案。

I was told whenever a class contains a pointer as a member, I should allocate memory for it.有人告诉我,每当 class 包含一个指针作为成员时,我应该为它分配 memory。 (and then use 'delete' inside the destructor to free the space) (然后在析构函数中使用'delete'来释放空间)

class Person{
    public:
    string* ptr_name;
    Person(string& name){
        ptr_name = new string(name);
    }
...
}

I was thinking if I can just do this instead我在想我是否可以这样做

class Person{
    public:
    string* ptr_name;
    Person(string name){
        ptr_name = &name;
    }
...
}

As I didn't use '&' inside the constructor argument, 'name' is copied by value inside the constructor.由于我没有在构造函数参数中使用“&”,因此“名称”在构造函数中按值复制。 So memory is already allocated for it.所以 memory 已经分配给它了。 The explicit destructor will be unnecessary since the pointer will be automatically destroyed on stack.显式析构函数将是不必要的,因为指针将在堆栈上自动销毁。

Would this work?这行得通吗?

After calling this constructor调用此构造函数后

Person(string name){
    ptr_name = &name;
}

the pointer ptr_name will be invalid because the local variable name will be destroyed.指针ptr_name将无效,因为局部变量name将被破坏。

Thus dereferencing such a pointer will result in undefined behavior.因此,取消引用这样的指针将导致未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM