Search code examples
c++placement-new

invoking copy constructor inside other constructor


#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>
class A
{
public:
    std::string s;
    A()
    {
        s = "string";
        new(this)A(*this);
    }
};
int main()
{
    A a;
    std::cout<<a.s;
    return 0;
}

I get empty string in output. What does the C++ standard say about such behaviour?


Solution

  • There must be at least two problems here:

    • You try to initialize A with a copy of itself
    • Inside the constructor, A isn't yet fully constructed, so you cannot really copy it

    Not to mention that new(this) is suspect in itself.