7
#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?

eXXXXXXXXXXX2
  • 1,540
  • 1
  • 18
  • 32

2 Answers2

4

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • 1
    `new(this)` is fine. And assigning to something with a copy of itself is usually also guaranteed to work (a copy assignment operator needs to guard against self-assignment) – copy construction, on the other hand, is a different matter. – Konrad Rudolph Mar 19 '12 at 11:03
  • @Konrad: So default (generated) copy ctor is guarded against self-assignment and therefore actual copying isn't performed? Seems that intermediate variable A a(*this); new(this)(a); solves the "problem" ? – user396672 Mar 19 '12 at 12:47
  • @user396672 Nothing of the sort. The default *copy assignment operator* guards against self-assignment. I don’t think the default copy constructor does, simply because this case should normally never occur. – Konrad Rudolph Mar 19 '12 at 13:15
0

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).

Alexandre C.
  • 55,948
  • 11
  • 128
  • 197