shared_ptr奇怪的行为

问题描述 投票:1回答:1

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

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;
c++ smart-pointers
1个回答
4
投票

我想知道为什么变量“t”在shared_ptr的重新分配应该销毁该对象时仍然打印一个值。

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

 - 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)
© www.soinside.com 2019 - 2024. All rights reserved.