我有一个类,它有几个int和一个const int成员,并定义了一个构造函数。
class SomeContainer
{
public:
SomeContainer():
member1(0),
member2(staticMethod())
{}
private:
static int staticMethod();
int member1;
const int member2;
}
我需要创建一个赋值操作符,因为我在另一个类MainClass和代码
中使用了这个类MainClass* p1;
MainClass* p2
{
//...
*p1 = *p2 // fails since SomeContainer doesn't have copy assignment operator
}
这段代码应该足够吗?还是我遗漏了什么?
{
SomeContainer(const SomeContainer& other): // copy ctor
member1(other.member1),
member2(other.member2)
{}
SomeContainer& operator=(const SomeContainer& other) // assignment operator
{
member1 = other.member1;
}
}
移动函数和移动赋值呢?我是否也需要实现这些?
首先,如果p1
和p2
是指针,那么您可以直接将它们赋值。
如果move构造函数不存在,则使用copy构造函数。
对于我来说,仍然很难理解允许对具有恒定非静态部分的东西进行赋值的逻辑含义。
你写的已经足够了
当不存在移动构造函数时,将使用复制构造函数来代替,这里的移动语义实际上没有任何意义。
如果真的需要赋值,就从成员中删除const