重载赋值运算符还是使用默认运算符?
Overloading the assignment operator or use the default one?
如果我有
Class A {
int x;
};
Class B {
vector<A> y;
//...
};
我想重载 B 中的赋值运算符 =
。使用默认的 =
运算符是否足够?它会在 y
成员上使用 vector
的 =
运算符吗?
编辑: 说我想自己实现类似的东西,这样如果 b 和 k 都是 B 类型,b = k 就可以工作。我需要显式调用在实现中释放 b 的 y 成员的向量析构函数?
它会是什么样子?
B& B::operator=(const B& b) {
if (this == &b) {
return *this;
}
y = b.y;
return *this;
}
这里会破坏原向量this->y
吗?为什么?
如果您没有特殊情况(比如拥有指针,或 unique_ptr
),您可以 not-define 它并使用默认的。你的情况应该没问题。
在拥有指针的情况下,你会突然有两个对象指向内存中的相同数据,这可能不是你想要的行为(同样适用于 shared_ptr
.
unique_ptr
无法复制,因此默认赋值运算符在这种情况下不起作用,您必须编写重载。
Will using the default =
operator be enough?
是的,足够了,除非你有任何需要特殊处理或参数的资源。
Will it just use the =
operator of vector on y member?
是的,生成的默认赋值 operator/copy 构造函数将自动调用成员变量可用的任何赋值 operators/copy 构造函数。
B& B::operator=(const B& b) {
if (this == &b) {
return *this;
}
y = b.y;
return *this;
}
Will the original vector this->y destructed here? why?
是的,它将是 "destructed",因为 vector<A>
的 operator=()
定义暗示这样做。
并不是真的调用了析构函数,但是赋值运算符的实现确实暗示了与构造新实例相同的行为,并且在清除向量时将调用所有包含的成员析构函数.
如果我有
Class A {
int x;
};
Class B {
vector<A> y;
//...
};
我想重载 B 中的赋值运算符 =
。使用默认的 =
运算符是否足够?它会在 y
成员上使用 vector
的 =
运算符吗?
编辑: 说我想自己实现类似的东西,这样如果 b 和 k 都是 B 类型,b = k 就可以工作。我需要显式调用在实现中释放 b 的 y 成员的向量析构函数?
它会是什么样子?
B& B::operator=(const B& b) {
if (this == &b) {
return *this;
}
y = b.y;
return *this;
}
这里会破坏原向量this->y
吗?为什么?
如果您没有特殊情况(比如拥有指针,或 unique_ptr
),您可以 not-define 它并使用默认的。你的情况应该没问题。
在拥有指针的情况下,你会突然有两个对象指向内存中的相同数据,这可能不是你想要的行为(同样适用于 shared_ptr
.
unique_ptr
无法复制,因此默认赋值运算符在这种情况下不起作用,您必须编写重载。
Will using the default
=
operator be enough?
是的,足够了,除非你有任何需要特殊处理或参数的资源。
Will it just use the
=
operator of vector on y member?
是的,生成的默认赋值 operator/copy 构造函数将自动调用成员变量可用的任何赋值 operators/copy 构造函数。
B& B::operator=(const B& b) { if (this == &b) { return *this; } y = b.y; return *this; }
Will the original vector this->y destructed here? why?
是的,它将是 "destructed",因为 vector<A>
的 operator=()
定义暗示这样做。
并不是真的调用了析构函数,但是赋值运算符的实现确实暗示了与构造新实例相同的行为,并且在清除向量时将调用所有包含的成员析构函数.