c – 从*值转换为rvalue方法?

c – 从*值转换为rvalue方法?,第1张

概述在C 11中,方法可以重载,表示方法被调用的对象的表达式是否为左值或右值.如果我从一个通过rvalue调用的方法返回*,我需要明确地从*这个或者不是? Foo Foo::method() &&{ return std::move(*this); // Is this move required or not?} 不幸的是,我不能简单地测试这个在我的编译器,因为g不支持这个功能:( 在C 11中,方法可以重载,表示方法被调用的对象的表达式是否为左值或右值.如果我从一个通过rvalue调用的方法返回*,我需要明确地从*这个或者不是?
Foo Foo::method() &&{    return std::move(*this);   // Is this move required or not?}

不幸的是,我不能简单地测试这个在我的编译器,因为g不支持这个功能:(

解决方法 这个类型总是一个左派:

§9.3.2[class.this] p1

In the body of a non-static (9.3) member function,the keyword this is a prvalue Expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. […]

§5.3.1[expr.unary.op] p1

The unary * operator performs indirection: the Expression to which it is applIEd shall be a pointer to an object type,or a pointer to a function type and the result is an lvalue referring to the object or function to which the Expression points.

所以你需要std :: move如果你想调用move构造函数.

以下代码片段显示:

#include <iostream>#include <utility>struct test{  test(){}  test(test const&){ std::cout << "copy ctor // #1\n"; }  test(test&&){ std::cout << "move ctor // #2\n"; }  test f_no_move() &&{ return *this; }  test f_move() &&{ return std::move(*this); }};int main(){  test().f_no_move(); // #1  test().f_move(); // #2}

使用Clang 3.1(我知道实现ref-qualifIErs的唯一编译器),我得到以下输出:

$clang++ -std=c++0x -stdlib=libc++ -pedantic -Wall t.cpp $./a.out copy ctor // #1 move ctor // #2

总结

以上是内存溢出为你收集整理的c – 从*值转换为rvalue方法?全部内容,希望文章能够帮你解决c – 从*值转换为rvalue方法?所遇到的程序开发问题。

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

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

原文地址:https://54852.com/langs/1233034.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存