指向有关初始化的类类型的指针

pointer to a class type about initialization

本文关键字:指针 类型 初始化      更新时间:2023-10-16
#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;
}

当我使用*c=*b它不起作用时,我认为它也使用operator(const B& b),但是当我使用new(c)B(*b)时,它没关系。

*c=*bnew(c)B(*b)有什么区别,为什么*c=*b错了?

您的代码:

B* b;
B* c;

现在bc是单元化的,这意味着不知道它们指向的内存地址。

当您执行以下操作时:

*b = a;

它将该未知地址的值更改为 a 的值。 这会导致undefined behavior.

然后你做:

*c = *b;

它基本上将未知地址的值设置为 c 未知地址的值b此时"可能"仍然是 a 的值,但它是未知的。

原因

new (c)B(*b);

正在起作用,是undefined behavior的黑暗魔法。

相关文章: