以下...
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 调用的中间。
看不到代码有任何明显错误。还有人看到这个吗?想法?