std :: make_shared的变量版本在iOS中调用析构函数

时间:2013-06-24 04:05:57

标签: ios c++11 destructor variadic-templates make-shared

以下......

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调用的中间。

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

1 个答案:

答案 0 :(得分:2)

您是否指定了-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