如何执行移动构造函数(C )的呼叫

How to enforce a calling of a moving constructor (C++)?

本文关键字:呼叫 构造函数 移动 执行 何执行      更新时间:2023-10-16

我有这两个代码线:

#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))
{}