C++ 共享ptr和删除测试

C++ 共享ptr和删除测试,c++,shared-ptr,C++,Shared Ptr,下面是代码: class TestApp {}; int main() { TestApp* test= new TestApp; { std::shared_ptr<TestApp> testPtr (test); } delete test; } 类TestApp{}; int main() { TestApp*测试=新TestApp; { std::共享测试ptr(测试); } 删除测试; } 问题是:为什么这个应用程序

下面是代码:

class TestApp {};

int main()
{
    TestApp* test= new TestApp;

    {
        std::shared_ptr<TestApp> testPtr (test);
    }

    delete test;
}
类TestApp{};
int main()
{
TestApp*测试=新TestApp;
{
std::共享测试ptr(测试);
}
删除测试;
}
问题是:为什么这个应用程序不会在“删除测试”时崩溃?否则,当我移除范围括号时会崩溃

因为。尝试删除已删除的内容会导致UB。您的两个用例都是错误的,会导致UB

您可能正在使用g++并收到以下消息:

Error in `./a.out': double free or corruption (fasttop): 0x00000000010eac20

如果使用Visual C++编译器,你会看到一个类似的异常。有大括号或没有大括号。

它在所有情况下都是错误的(有{}和没有{}),因为你2次调用
delete test
-inside
~shared\u ptr
析构函数和explicit。如果它没有崩溃,没有什么可以说未定义的行为是未定义的。@Ville Valtteri-我想不完全是这样。在您的链接的具体示例中,可以随时调用带有具体类的具体析构函数,而不会发生崩溃或ub,因为这里并没有任何东西可以阻止多次调用它。这里的任务在2次调用<代码>删除测试-释放我们已经不拥有的内存(第一次删除后)已经100%错误