Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 216
eXXXXXXXXXXX2 Avatar asked Mar 19 '12 10:03

eXXXXXXXXXXX2


1 Answers

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.

like image 166
Bo Persson Avatar answered Nov 07 '22 16:11

Bo Persson