加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 移动语义和临时隐含此

发布时间:2020-12-16 09:47:07 所属栏目:百科 来源:网络整理
导读:当对象*这实际上是临时的时,是否可以创建不同的方法? 例如: #include iostreamstruct BigObj{ void changeFast() {}};class A { BigObj obj;public: A(){} A(const A a) { obj = a.obj; std::cout "copyn"; } A(A a) { obj = std::move(a.obj); std::cout
当对象*这实际上是临时的时,是否可以创建不同的方法?

例如:

#include <iostream>

struct BigObj{
    void changeFast() {}
};

class A {
    BigObj obj;
public:
    A(){}
    A(const A& a) {
        obj = a.obj;
        std::cout << "copyn";
    }
    A(A&& a) {
        obj = std::move(a.obj);
        std::cout << "moven";
    }
    A changed() {
        A ret = *this; //(1)
        ret.obj.changeFast();
        return ret;
    }
};

int main(){
    A a;
    A b = std::move(a).changed();
    (void)b;
    return 0;
}

在第(1)行,我们有副本,但并不是真的需要.但我们不能总是搬到这里,因为有时方法不是临时的.应该怎样做才能避免复制?

如果它不是方法,只是函数可以写入类似的函数:

A changed(const A& a){
}

A changed(A&& a){
}

解决方法

您可以在* this的r值上重载函数.例如:

class A
{
public:
    // ... 
    A changed() const&; // called for l-values
    A changed() &&;     // called for r-values
};

但是,如果没有参考资格,则不能使具有参考资格的版本超载.见13.1 [over.load]第2段,第3点子弹:

Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name,the same parameter-type-list,and the same template parameter lists cannot be overloaded if any of them,but not all,have a ref-qualifier (8.3.5).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读