gpt4 book ai didi

c++ - 重载赋值运算符还是使用默认运算符?

转载 作者:行者123 更新时间:2023-11-30 01:12:13 25 4
gpt4 key购买 nike

如果我有

Class A {
int x;
};

Class B {
vector<A> y;
//...
};

我想重载 B 中的赋值运算符 =。使用默认的 = 运算符是否足够?它会在 y 成员上使用 vector= 运算符吗?

编辑:说我想自己实现类似的东西,这样如果 b 和 k 都是 B 类型,b = k 就可以工作。我是否需要显式调用 vector 析构函数来释放b 的 y 成员,在实现中?

它会是什么样子?

B& B::operator=(const B& b) {
if (this == &b) {
return *this;
}
y = b.y;
return *this;
}

原始 vector this->y会在这里被破坏吗?为什么?

最佳答案

Will using the default = operator be enough?

是的,这就足够了,除非您有任何需要特殊处理或参数的资源。

Will it just use the = operator of vector on y member?

是的,生成的默认赋值运算符/复制构造函数将自动调用成员变量可用的任何赋值运算符/复制构造函数。


 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?

是的,它将被“破坏”,因为operator=() vector<A>的定义|暗示这样做。

并不是真的调用了析构函数,但赋值运算符的实现确实暗示了与构造新实例相同的行为,并且在清除 vector 时将调用所有包含的成员析构函数。

关于c++ - 重载赋值运算符还是使用默认运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34579877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com