这是创建具有引用成员的赋值运算符的有效方法吗?
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
它似乎编译并运行良好,但是当c ++倾向于表现出最不期望的未定义行为时,以及所有说它不可能的人,我认为我错过了一些问题.我错过了什么吗?
Jam*_*nze 37
它的语法正确.但是,如果放置新的抛出,则最终会得到一个无法破坏的对象.如果有人来自你的班级,更不用说灾难了.只是不要这样做.
解决方案很简单:如果类需要支持赋值,请不要使用任何引用成员.我有很多带有引用参数的类,但是将它们存储为指针,这样类就可以支持赋值.就像是:
struct A
{
int* myRef;
A( int& ref ) : myRef( &ref ) {}
// ...
};
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用reference_wrapper类(在函数头中):
struct A
{
A(int& a) : a_(a) {}
A(const A& a) : a_(a.a_) {}
A& operator=(const A& a)
{
a_ = a.a_;
return *this;
}
void inc() const
{
++a_;
}
std::reference_wrapper<int>a_;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12118 次 |
| 最近记录: |