/*
Constructor initializing a string pointer
*/
class Person {
public:
Person(string name) :pName(new string(name)) {
//pName = new string(name);
}
~Person() { delete pName; }
void printName() { cout << *pName << endl; }
private:
string* pName;
};
int main() {
vector<Person> persons;
persons.push_back(Person("p1"));
persons.front().printName();
cout<<"Good bye"<<endl;
return 0;
}
Asked
Active
Viewed 34 times
0

MikeCAT
- 73,922
- 11
- 45
- 70
-
3Follow [The Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) by adding definition of copy constructor and assignment operator to avoid troubles on copying. – MikeCAT Jun 12 '21 at 02:56
-
Please review [ask] for advice on how to write a good question. – JaMiT Jun 12 '21 at 03:07
-
Does the string variable really need to be a pointer to a string? If you had a string member instead you could use the rule of zero. – drescherjm Jun 12 '21 at 03:19
1 Answers
1
I might not have this entirely correct but the reason this is happening is as follows..
Person("p1")
creates a temporary person with a pointer to the string "p1"
. persons.push_back()
copies that object into the vector. This is only a shallow copy so the new object's pointer will point to the memory location of the temporary object's string which gets destroyed so you're accessing invalid memory.
You can do persons.emplace_back("p1");
which creates the object in place in the vector so no copying takes place; however, as the comments point out, if you are managing memory yourself then you need to apply the rule of 3 and implement copy and assignment constructors as well as the destructor.

matdon
- 146
- 6