我在学习c++,发现一个我不明白的问题。我有这个简单的代码:
#include <iostream>
#include <vector>
class Person
{
string * name;
public:
Person(const string & n) : name {new string {n}} {}
~Person() {delete name;}
string getName() const {return *name;}
};
int main()
{
vector<Person> people;
people.push_back(Person("Tom"));
cout << "Name is: " << people.back().getName() << endl;
return 0;
}
当我运行它时,我没有输出。不知道为什么?然而,当我做类似的事情,但没有 vector 时,一切正常:
int main()
{
Person tom {"Tom"};
cout << "Name is: " << tom.getName() << endl;
return 0;
}
最佳答案
正如其他人所说,最好不要使用指针。然而,如果你想知道发生了什么,你得到的原因是在这一行 people.push_back(Person("Tom"));
Person 对象被创建,并且它的拷贝传递给 vector .但是,一旦复制了对象,就会执行删除字符串的析构函数。
通过使用指针,原始 Person 对象及其拷贝都指向内存中的同一个字符串。字符串被析构函数删除,拷贝中的 name
指针不指向任何内容。因此你会得到未定义的行为。
要纠正这个问题,要么不要使用指针,要么您需要定义自己的复制构造函数。例如:
class Person
{
string * name;
public:
Person(const string & n) : name {new string {n}} {}
// copy constructor which makes new string in memory
//based on the original string.
Person(const Person & other) {
name = new string(other.getName());
}
~Person() { delete name; }
string getName() const {return *name;}
};
关于c++ - Cout 不返回任何输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28467564/