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

c – 移动语义和临时隐含此,第1张

概述当对象*这实际上是临时的时,是否可以创建不同的方法? 例如: #include <iostream>struct BigObj{ void changeFast() {}};class A { BigObj obj;public: A(){} A(const A& a) { obj = 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 << "copy\n";    }    A(A&& a) {        obj = std::move(a.obj);        std::cout << "move\n";    }    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点子d:

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).

总结

以上是内存溢出为你收集整理的c – 移动语义和临时隐含此全部内容,希望文章能够帮你解决c – 移动语义和临时隐含此所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1215358.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存