具有引用成员的赋值运算符 [英] Assignment operator with reference members

查看:31
本文介绍了具有引用成员的赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是创建具有引用成员的赋值运算符的有效方法吗?

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 ) {}
    // ...
};

这篇关于具有引用成员的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆