eXXXXXXXXXXX2
eXXXXXXXXXXX2

Reputation: 1580

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?

Upvotes: 7

Views: 210

Answers (2)

Alexandre C.
Alexandre C.

Reputation: 56956

You are calling s's constructor twice in a row by doing this, ergo, the behavior is undefined (and most likely some memory is leaked).

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92261

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.

Upvotes: 4

Related Questions