为什么复制构造函数更改了以前的对象指针成员

Why copy constructor changed previous object pointer member

提问人:xianshenglu 提问时间:1/17/2023 更新时间:1/17/2023 访问量:69

问:

#include <iostream>
#include <string.h>
#include "Date.h"
#include "Employee.h"
using std::cout;
using std::endl;
using std::to_string;

class TestOps {
public:
    int sex = 1;
    string toString() {
        return " sex:" + to_string(sex) ;
    }
};
class Test {
public:
    TestOps* testOps;
    Test(const Test& t) :Test{} {
        this->testOps = new TestOps{ *(t.testOps) };
    };
    Test()  {
        TestOps ops;
        //this->testOps = new TestOps{}; // it will be ok with this way
        this->testOps = &ops;
    }
};

int main() {
    // code not understand
    Test t1;
    cout <<"first testOps:" << t1.testOps->toString() << endl; // sex: 1
    Test t2{ t1 };
    cout << "first testOps:" << t1.testOps->toString() << endl; // sex: -858893460 ???? why?
    cout << "second testOps:" << t2.testOps->toString() << endl; // sex:  -858893460 ???? why?

    return 0;
}

如您所见,为什么第一个日志符合预期,而后面的日志则不符合预期?

此外,地址与预期的地址不同。t1.testOpst2.testOps

我做了一些研究,但没有找到答案。也许是因为我对 cpp 很陌生。

C++ 复制构造函数

评论

6赞 Yksisarvinen 1/17/2023
ops在构造函数结束时死亡,对它的任何访问都会导致未定义的行为。Test
0赞 NathanOliver 1/17/2023
您的代码具有未定义的行为。 设置为指向一个对象,该对象将在构造函数结束时立即销毁。this->testOps = &ops;tesOps
0赞 molbdnilo 1/17/2023
存储您获取的指针以备后用(几乎)总是一个坏主意。&
0赞 PaulMcKenzie 1/17/2023
我做了一些研究,但没有找到答案——你做了什么研究?存储局部变量的地址,然后在该变量超出范围后尝试访问该地址,是基本的 C++ 知识。如果你通过使用谷歌或一些视频来学习C++,那么,对于如此困难的语言来说,这不会太好。
0赞 Konrad Rudolph 1/17/2023
@molbdnilo 相反:在现代高级C++中,您存储的绝大多数原始指针都将指向具有自动存储功能的对象,因此将通过运算符获取。&

答: 暂无答案