c++ – Using new(this)

Question:

Читаю C++ Super-FAQ. В разделе Constructors натыкаюсь такое высказывание:

BTW do NOT try to achieve this via placement new. Some people think
they can say new(this) Foo(x, int(x)+7) within the body of
Foo::Foo(char). However that is bad, bad, bad. Please don’t write me
and tell me that it seems to work on your particular version of your
particular compiler; it’s bad

Речь идет о том, то что так делать категорически нельзя:

class Foo{
public:
    Foo(char x){
        new (this) Foo(x, int(x)+7); 
    }
    Foo(char x, int y){
        //...
    }
};

Can anyone explain in more detail what this trick threatens?

UPD: I suspect that in this example everything will be fine, and problems will begin with inheritance, dynamic resource allocation, etc.

Answer:

http://ideone.com/gkgi7S :

class Base
{
public:
    Base()  { ptr = new int[100]; cout << "alloc mem at " << ptr << endl; }
    ~Base() { delete [] ptr; cout << "free mem at " << ptr << endl; }
    int * ptr;
};

class Derived: public Base
{
public:
    Derived(int x, int y):x(x),y(y){}
    Derived(int x)
    {
        new(this) Derived(x,0);
    }
    int x, y;
};

int main(int argc, const char * argv[])
{
    Derived d(5);
}

Conclusion:

alloc mem at 0070EA58
alloc mem at 0070FFE8
free mem at 0070FFE8

Is this example enough?

It is possible without inheritance – the essence does not change:

class Derived
{
public:
    Derived(int x, int y):x(x),y(y){}
    Derived(int x)
    {
        new(this) Derived(x,0);
    }
    int x, y;
    Base b;
};
Scroll to Top