【发布时间】:2015-02-26 05:58:12
【问题描述】:
我对具有结构和指针成员变量的类的复制构造函数和赋值构造函数有以下查询。
这是我的课
class myClass{
public:
Calculator mCalc; // Calculator is a class that I defined elsewhere
struct Sstatus{
bool add_flag;
int error_code;
CvMat* matrix; // I am using OpenCV here for matrix handle
double params[6];
};
// class function
myClass(void);
~myClass(void);
protected:
int index;
BasedClass* interface;
CvMat* matrix_int;
private:
int calc_index;
bool* done;
};
而我的类函数如下
myClass::myClass(void):mCalc(0),
index(0),
matrix_int(0),
calc_index(0),
done(0)
{
interface = new DerivedClass(); // derived class is extended by the base class
}
myClass::~myClass(void){
delete interface;
}
// defining copy constructor
myClass::myClass(const myClass& o):mCalc(o.mCalc),
index(o.index),
calc_index(o.calc_index),
done(o.done)
{
// assigning new memory for member pointers for copying
matrix_int = new CvMat();
*matrix_int = o.matrix_int;
interface = new DerivedClass();
*interface = o.interface;
done = new bool();
*bool = o.done;
}
// defining assignment operator
myClass::myClass& operator=(const myClass& o)
{
if(this != &o)
{
mCalc = o.mCalc;
index = o.index;
calc_index = o.calc_index;
// assigning new memory for member pointers for copying
matrix_int = new CvMat();
*matrix_int = o.matrix_int;
interface = new DerivedClass();
*interface = o.interface;
done = new bool();
*bool = o.done;
}
return *this;
}
我有几个问题
- 复制构造函数和赋值运算符应该这样编码吗?对于成员指针和数组,应该怎么做
- 我不太明白指针成员的赋值和复制构造函数之间的区别。跟我很像
- 如果我们要为结构体定义一个拷贝构造函数和赋值构造函数,应该怎么做呢?
谢谢
其他问题:如果我在复制构造函数中使用了 new,是否需要在析构函数中删除它?
【问题讨论】:
-
不,这不是你应该编写资源拥有类的方式,使用智能指针 (
unique_ptr) 来管理动态分配的成员。您看不到复制赋值和复制构造之间的区别,因为在赋值运算符的情况下,您正在泄漏数据成员已经指向的内存。阅读copy and swap idiom,在大多数情况下,这应该是您实现复制构造函数/复制赋值运算符的方式。 -
从未见过指向
bool的指针。为什么会这样? -
@Praetorian 不要再说当他想要动态管理内存时应该使用智能指针。这不是行业或其他什么...
-
@nbro 是的,很好的建议,干得好。坚持下去。
-
*bool = o.done;??
标签: c++ pointers structure copy-constructor deep-copy