gpt4 book ai didi

ios - iOS 中 std::make_shared 调用析构函数的可变版本

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:13:16 24 4
gpt4 key购买 nike

以下...

class TestClass
{
public:

TestClass(const char* szParam, int nParam)
: m_strParam(szParam)
, m_nParam(nParam)
{
Dbg_Printf("2 param constructor - %s, %d\n", m_strParam.c_str(), m_nParam);
}

TestClass()
: m_strParam("Default")
, m_nParam(0)
{
Dbg_Printf("0 param constructor - %s, %d\n", m_strParam.c_str(), m_nParam);
}

virtual ~TestClass()
{
Dbg_Printf("Destructor - %s, %d\n", m_strParam.c_str(), m_nParam);
m_strParam.clear();
m_nParam = 0;
}

std::string m_strParam;
int m_nParam;
};


void Test()
{
Dbg_Printf("Start\n");
{
Dbg_Printf("Allocating 0 param TestClass\n");
auto pTest_0Params = std::make_shared<TestClass>();
Dbg_Printf("Done allocating, going out of scope\n");
}

{
Dbg_Printf("Allocating 2 param TestClass\n");
const char* szTest = "2 param";
int foo = 2;
auto pTest_2Params = std::make_shared<TestClass>(szTest, foo);
Dbg_Printf("Done allocating, going out of scope\n");
}
Dbg_Printf("Done\n");
}

产生以下结果

Start
Allocating 0 param TestClass
0 param constructor - Default, 0
Done allocating, going out of scope
Destructor - Default, 0
Allocating 2 param TestClass
2 param constructor - 2 param, 2
Destructor - 2 param, 2
Destructor - 2 param, 2
Done allocating, going out of scope
Destructor - 2 param, 2
Done

对 make_shared 的 2 参数调用最终在分配和赋值时调用析构函数两次。

我已经用析构函数中的断点一次又一次地调试了。它在 2 参数情况下的 make_shared 调用的中间。

看不到代码有任何明显的错误。还有其他人看到这个吗?想法?

最佳答案

你有指定-std=c++11吗?

当我在桌面上编译时:

clang++ -std=c++03 -stdlib=libc++ test.cpp

我得到你得到的:

Start
Allocating 0 param TestClass
0 param constructor - Default, 0
Done allocating, going out of scope
Destructor - Default, 0
Allocating 2 param TestClass
2 param constructor - 2 param, 2
Destructor - 2 param, 2
Destructor - 2 param, 2
Done allocating, going out of scope
Destructor - 2 param, 2
Done

但是当我打开 -std=c++11 我得到:

Start
Allocating 0 param TestClass
0 param constructor - Default, 0
Done allocating, going out of scope
Destructor - Default, 0
Allocating 2 param TestClass
2 param constructor - 2 param, 2
Done allocating, going out of scope
Destructor - 2 param, 2
Done

关于ios - iOS 中 std::make_shared 调用析构函数的可变版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17267881/

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