c++ - Cout 不返回任何输出

标签 c++

我在学习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/

相关文章:

c++ - 从用户输入中删除数组

c++ - 调用 CreateWindow() func WinApi 时出现错误 1813

c++ - typedef 函数指针?

c++ - 如何在 C++ 中将动态二维字符串数组作为参数传递

c++ - 如何通过带有 UARTSerial 类的 USB 在 nucleo f446re 和 mbed 之间发送字节数组?

c++ - 长度为 20 的 Cout'ing 数组输出 23 个字符

c++ - 将 div 与无符号整数一起使用

c++ - directx C++ 第一人称相机

c++ - 我得到断言失败 "file_name != nullptr"但仅在 Release模式下

C++ 无法将 lambda 转换为 std::pair 中的 std::packaged_task