Assignment operator with reference members(具有引用成员的赋值运算符)
问题描述
这是创建具有引用成员的赋值运算符的有效方法吗?
Is this a valid way to create an assignment operator with members that are references?
#include <new>
struct A
{
int &ref;
A(int &Ref) : ref(Ref) { }
A(const A &second) : ref(second.ref) { }
A &operator =(const A &second)
{
if(this == &second)
return *this;
this->~A();
new(this) A(second);
return *this;
}
}
它似乎编译和运行良好,但是由于 c++ 倾向于在最不期望的情况下显示未定义的行为,而且所有的人都说这是不可能的,我想我错过了一些问题.我错过了什么吗?
It seems to compile and run fine, but with c++ tendency to surface undefined behavior when least expected, and all the people that say its impossible, I think there is some gotcha I missed. Did I miss anything?
推荐答案
它在语法上是正确的.但是,如果放置 new 抛出,您最终得到一个你无法破坏的对象.更别说灾难了如果有人从你的班级派生出来.只是不要这样做.
It's syntactically correct. If the placement new throws, however, you end up with an object you can't destruct. Not to mention the disaster if someone derives from your class. Just don't do it.
解决办法很简单:如果类需要支持赋值,就不要使用任何参考成员.我有很多课程可以参考参数,但将它们存储为指针,以便类可以支持任务.类似的东西:
The solution is simple: if the class needs to support assignment, don't use any reference members. I have a lot of classes which take reference arguments, but store them as pointers, just so the class can support assignment. Something like:
struct A
{
int* myRef;
A( int& ref ) : myRef( &ref ) {}
// ...
};
这篇关于具有引用成员的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有引用成员的赋值运算符


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01