Home > Blockchain >  C pointer member initialization
C pointer member initialization

Time:12-28

I know this is really basic, but I don't know the answer given my very limited C usage.

I was told whenever a class contains a pointer as a member, I should allocate memory for it. (and then use 'delete' inside the destructor to free the space)

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. The explicit destructor will be unnecessary since the pointer will be automatically destroyed on stack.

Would this work?

CodePudding user response:

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.

Thus dereferencing such a pointer will result in undefined behavior.

  • Related