-2
#include <iostream>
using namespace std;
class B{
public:
    int date;
    B(){cout<<"B()"<<endl;}
    B(int a){date=a;cout<<"B(int a)"<<endl;}
    B(const B& b){
        date=b.date;
        cout<<"int date;"<<endl;
    }
    B& operator =(const B& b){
        date=b.date;
        cout<<"operator(const B& b)"<<endl;
        return *this;
    }
    void print(){
        std::cout<<date<<std::endl;
    }
};
int main(){
    B a(1);//use B(int a)
    B* b;
    B* c;
    *b=a;//use operator(const B& b)
    *c=*b;//but this one is wrong,why?,I think it also use operator(const B& b)
    new (c)B(*b);
    return 0;
}

When I use *c=*b it doesn't work, I think it also uses operator(const B& b), but when I use new(c)B(*b) it is ok.

What is the difference between *c=*b and new(c)B(*b) and why is *c=*b wrong?

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
tmh
  • 7
  • 4

1 Answers1

2

Your code:

B* b;
B* c;

Now b and c are unitialized, which means that it is unknown to what memory address they are pointing to.

When you do:

*b = a;

It changes the value at that unknown address to the value of a. Which causes undefined behavior.

Then you do:

*c = *b;

Which basically sets value at unknown address c to value of unknown address b which at this point 'might' still be value of a, but it is unknown.

The reason why

new (c)B(*b);

is working, is the dark magic of undefined behavior.

Neijwiert
  • 985
  • 6
  • 19