右值成员也是右值吗?
Are Rvalue members indeed Rvalues too?
本文关键字:成员 更新时间:2023-10-16
他们说右值的成员也是右值——这很有意义。因此,这要么是vc++特有的错误,要么是我对右值的理解中的错误。
拿这个玩具代码:
#include <vector>
#include <iostream>
using namespace std;
struct MyTypeInner
{
MyTypeInner() {};
~MyTypeInner() { cout << "mt2 dtor" << endl; }
MyTypeInner(const MyTypeInner& other) { cout << "mt2 copy ctor" << endl; }
MyTypeInner(MyTypeInner&& other) { cout << "mt2 move ctor" << endl; }
const MyTypeInner& operator = (const MyTypeInner& other)
{
cout << "mt2 copy =" << endl; return *this;
}
const MyTypeInner& operator = (MyTypeInner&& other)
{
cout << "mt2 move =" << endl; return *this;
}
};
struct MyTypeOuter
{
MyTypeInner mt2;
MyTypeOuter() {};
~MyTypeOuter() { cout << "mt1 dtor" << endl; }
MyTypeOuter(const MyTypeOuter& other) { cout << "mt1 copy ctor" << endl; mt2 = other.mt2; }
MyTypeOuter(MyTypeOuter&& other) { cout << "mt1 move ctor" << endl; mt2 = other.mt2; }
const MyTypeOuter& operator = (const MyTypeOuter& other)
{
cout << "mt1 copy =" << endl; mt2 = other.mt2; return *this;
}
const MyTypeOuter& operator = (MyTypeOuter&& other)
{
cout << "mt1 move =" << endl; mt2 = other.mt2; return *this;
}
};
MyTypeOuter func() { MyTypeOuter mt; return mt; }
int _tmain()
{
MyTypeOuter mt = func();
return 0;
}
这段代码输出:
也就是说,MyTypeOuter的move函数调用MyTypeInner的copy,而不是move。如果我将代码修改为:mt2 copy =
mt1井底扭矩
是井底扭矩
MyTypeOuter(MyTypeOuter&& other)
{ cout << "mt1 move ctor" << endl; mt2 = std::move(other.mt2); }
输出如预期:
mt2 move =
mt1井底扭矩
是井底扭矩
似乎vc++(2010和2013)不尊重这部分标准。还是我错过了什么?
rvalue
的成员是否为rvalue
不是这里的问题,因为您正在处理赋值操作符中的左值。
在这个move赋值操作符中,
const MyTypeOuter& operator = (MyTypeOuter&& other)
{
cout << "mt1 move =" << endl;
mt2 = other.mt2;
return *this;
}
other
是一个lvalue
(因为它有一个名字),通过扩展other.mt2
也是。当您说mt2 = other.mt2
时,您只能调用标准赋值操作符。
为了调用move构造函数,您需要使other.mt2
看起来像右值,这就是std::move
所实现的:
const MyTypeOuter& operator = (MyTypeOuter&& other)
{
cout << "mt1 move =" << endl;
mt2 = std::move(other.mt2);
return *this;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗