如何执行移动构造函数(C )的呼叫
How to enforce a calling of a moving constructor (C++)?
我有这两个代码线:
#include <iostream>
using namespace std;
class A
{
public:
A() noexcept
{
cout << "A::A()" << endl;
}
A(const A&) noexcept
{
cout << "A::A(const A&)" << endl;
}
A(A&&) noexcept
{
cout << "A::A(A&&)" << endl;
}
};
class B
{
public:
B(const A& a) noexcept :
_a(a)
{}
B(A&& a) noexcept :
_a(a)
{}
private:
A _a;
};
int main(int argc, char* argv[])
{
A a;
B b1 = B(a);
B b2 = B(A());
}
他们产生此输出:
A::A()
A::A(const A&)
A::A()
A::A(const A&)
从 B::B(A&&)
调用A::A(A&&)
,我需要做什么?
您可以看到添加noexcept
无法解此问题。
尽管a
的类型是对A
的RVALUE引用,但a
本身是lvalue。要保留其rvalue-ness,您需要使用std::move
:
B(A&& a) noexcept :
_a(std::move(a))
{}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 错误:呼叫构造器的匹配函数无匹配功能
- 匿名构造函数和击曲函数在矢量中呼叫
- 在类构造函数上没有匹配函数来呼叫错误
- C 使用lambda进行隐式构造函数呼叫期望函数指针
- 您能否防止构造函数的呼叫,而无需实例化
- C 错误:在自定义类的构造函数呼叫期间使用已删除的函数
- 在构造函数中呼叫迭代器会更改其最终值
- 如何执行移动构造函数(C )的呼叫