带有参考成员的赋值运算符 [英] Assignment operator with reference members

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

问题描述

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

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?

推荐答案

从语法上讲这是正确的。但是,如果新的展示位置抛出,您
最终会遇到无法破坏的对象。更不用说如果有人从你的班级派生灾难
了。只是不要这样做。

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天全站免登陆