Temple
Temple

Reputation: 1631

Placement new overriding existing objects

If I would do placement new on objects that are already created on stack:

struct s{
s() { std::cout << "C\n";}
~s() { std::cout << "D\n";}
};

int main() {
        s s1[3];
        for(int i=0; i< 3; ++i)
                s* newS = new (&s1[i]) s();
}

I get:

C
C
C
C
C
C
D
D
D

So we are not getting destructors for first 3 objects, is that safe? If we just override memory for objects allocated on heap/stack and that objects do not have to free any resources in destructors is that still safe?

Upvotes: 2

Views: 763

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

wandbox example

Your output is not unexpected - placement new does not invoke the destructor of any potential object stored in the memory location you're accessing. You need to explictly invoke the destructor of any object that occupies the memory location you're trying to use in order to use placement new safely.

struct s
{
    s()
    {
        std::cout << "C\n";
    }
    ~s()
    {
        std::cout << "D\n";
    }
};

int main()
{
    // Three 's' instances are constructed here.
    s s1[3];

    // (!) You need to explicitly destroy the existing
    // instances here.
    for(int i = 0; i < 3; ++i)
    {
        s1[i].~s();
    }

    for(int i = 0; i < 3; ++i)
    {
        // Three 's' instances are constructed here.
        s* newS = new(&s1[i]) s();
    }

    // Three 's' instances are destroyed here.
}

Output:

C
C
C
D
D
D
C
C
C
D
D
D

Upvotes: 4

Related Questions