[英]Should you copy static data members in a copy constructor or assignment operator?
[英]How to deal with reference data-members in the assignment operator, and copy constructor?
我有以下课程
class TVData
{
private:
int ID;
Monitor& monitor;
string pName;
}
我需要实现赋值运算符 ,以及可用于此类的复制构造函数 。
TVData::monitor
? 您不能重新分配引用,因此,如果需要在赋值运算符中对其进行更改,则应使其成为指针-可以照常使用=
进行赋值,尽管仍然鼓励在复制构造函数中使用初始化程序列表...
TVData(const TVData& rhs)
: ID(rhs.ID), p_monitor(rhs.p_monitor), pNmae(rhs.pName)
{ }
介绍
要正确地将变量声明为声明的数据成员分配为引用,您将需要使用构造函数中的成员初始化列表 (在default-和copy-constructor中 )。
重载赋值运算符的问题在于,由于引用在初始化(必须初始化)之后无法绑定到新实体,因此在创建TVData
之后就无法更改该引用所指的TVData
。
如果您希望能够更改引用所指的内容,请考虑使用指针而不是引用。
样品实施
#include <iostream>
struct Obj {
Obj (int& r)
: ref (r)
{ }
Obj (Obj const& src)
: ref (src.ref)
{ }
Obj& operator= (Obj const& src) {
// we cannot reassign what `ref` is refering to,
// but we can at least assign the value of `src.ref`
// to `this->ref`
ref = src.ref; // note: does not make `ref` refer to `src.ref`
}
int& ref;
};
int
main (int argc, char *argv[])
{
int some_val = 0, some_other_val = 100;
Obj a (some_val);
Obj b (a); // copy `a`
Obj c (some_other_val);
b = c;
b.ref += 23;
std::cout << "some_val: " << some_val << std::endl;
}
some_val: 123
引用不可复制或不可移动,您必须回退到指针或reference_wrapper
首先,使用(非const)引用作为类成员是相当危险的,因为在这种情况下,您必须保证被引用的对象将比引用它的类的实例寿命更长。
其次,您可以为此类实现复制构造函数,但由于C ++引用不可重新绑定,因此无法进行赋值。
为了进行管理,您可能更喜欢根据类的分配语义使用shared_ptr / unique_ptr(它是应该共享拥有的Monitor还是通过所有权)。 如果您不拥有它,那么“ weak_ptr”(std ::或boost::)是最好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.