gpt4 book ai didi

c++ - shared_ptr 奇怪的行为

转载 作者:行者123 更新时间:2023-11-30 01:36:24 26 4
gpt4 key购买 nike

这是我做的第一个问题。我搜索了很多但找不到答案。我正在学习在 c++14 上使用智能指针,编译器是 g++5.4。我想知道为什么当 shared_ptr 的重新分配应该销毁该对象时变量“t”仍然打印一个值。正如在第二个示例中所做的那样。提前致谢!

shared_ptr<string> p = make_shared<string>("test1");
string& t = *p.get();
cout<<t<<endl;
p = make_shared<string>("test2");
cout<<t<<endl;
cout<<"Second Example\n";
string *p1 = new string("test1");
string& t1 = *p1;
cout<<t1<<endl;
delete p1;
cout<<t1<<endl;

最佳答案

I want to know why is the variable "t" still prints a value when the reassignment of the shared_ptr should destroy that object.

因为访问被销毁对象的行为是未定义的。可能的行为包括,但都不能保证:

 - working
- not working
- random output
- non-random output
- the expected output
- unexpected output
- no output
- any output
- crashing at random
- crashing always
- not crashing at all
- corruption of data
- different behaviour, when executed on another system
- , when compiled with another compiler
- , on tuesday
- , only when you are not looking
- same behaviour in any or all of the above cases
- anything else within the power of the computer (hopefully limited by the OS)

关于c++ - shared_ptr 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52239691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com