Gst*_*tso 1 c++ compiler-warnings
我将创建一些具有虚拟副本功能的父类和子类,它返回self的副本:
class A{
public:
int ID;
virtual A* copy(){
return new A();
}
}
class B : public A{
public:
int subID;
virtual A* copy(){
B* b=new B();
memcpy(b,this,sizeof(B));
return b;
}
};
Run Code Online (Sandbox Code Playgroud)
编译时,会显示以下警告:
destination for this 'memcpy' call is a pointer to dynamic class 'B' ; vtable pointer will be overwritten
explicitly cast the pointer to silence this warning
Run Code Online (Sandbox Code Playgroud)
这个警告意味着什么,它会带来什么潜在的问题?
这意味着这不起作用.不应该使用C库的memcpy()函数复制C++对象(在某些有限的情况下除外),它对C++类,它们的构造函数,析构函数,虚拟方法以及C++中不在C中的所有其他内容一无所知.
你想要的是一个复制构造函数.它的工作正是您要完成的任务:制作现有对象的副本.
virtual A* copy(){
B* b=new B(*this);
return b;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1241 次 |
| 最近记录: |