What is happening when I call a destructor from a placement new inside an std::vector?

Viewed 94

If I have the following

#include <vector>

class C
{
public:
    C()
    :
        m_d(new int)
    {
        *m_d = 2;
    }

    ~C()
    {
        delete m_d;
    }

    int* m_d;
};

int main()
{
    std::vector<char> data;

    data.resize(sizeof(C));

    C* newC = new(&data[0]) C;

    C* cAgain = reinterpret_cast<C*>(&data[0]);
    cAgain->~C();

    return 0;
}

What exactly happens? When the std::vector<char> is destroyed, has it freed the memory twice? If it hasn't, why hasn't it? If it has, how would you prevent it?

2 Answers

std::vector<char> data; handles its own memory which contains char, unrelated to C.

C* newC = new(&data[0]) C; call constructor of C, (which allocates).

When newC leaves scope, destructor of C is NOT called. (newC is just a pointer, not a C)

cAgain->~C(); call destructor of C (good). As for newC, when scope ends, no (extra) destructor of C is called.

So assuming correct alignment, and aliasing between newC and cAgain correct, your code is OK without leaks.

You have declared data as vector of char so the vector object works on data type of char not you class C so when it is destroyed no destructor will be called because char has no one.

so only one destructor is called ~C()

Related