Skip to content

Instantly share code, notes, and snippets.

@ZJUGuoShuai
Created May 17, 2023 11:20
Show Gist options
  • Select an option

  • Save ZJUGuoShuai/d26d80eae2228124a3e6633cf0ceb29a to your computer and use it in GitHub Desktop.

Select an option

Save ZJUGuoShuai/d26d80eae2228124a3e6633cf0ceb29a to your computer and use it in GitHub Desktop.
关于移动构造函数被调用次数的疑惑

关于移动构造函数被调用次数的疑惑

代码 1:

基本信息:

  • class A 具有拷贝构造和移动构造;
  • class B 支持从 A 构造。

main 中,尝试从一个 A 对象 a 构造一个 B 对象 b

#include <iostream>

class A {
public:
  A() = default;
  A(const A&) {
    std::cout << "A copy ctor" << std::endl;
  };
  A(A&&) {
    std::cout << "A move ctor" << std::endl;
  }
};

class B {
  A a_;
public:
  explicit B(A a): a_(a) {};
};


int main() {
  A a;
  B b{a};
  return 0;
}

编译运行:

$ g++ t.cc
$ ./a.out

结果符合预期,两次拷贝构造,一次是构造了 B Constructor 的参数,第二次是构造了 Ba_ 成员:

A copy ctor
A copy ctor

代码 2:

#include <iostream>

class A {
public:
  A() = default;
  A(const A&) {
    std::cout << "A copy ctor" << std::endl;
  };
  A(A&&) {
    std::cout << "A move ctor" << std::endl;
  }
};

class B {
  A a_;
public:
  explicit B(A a): a_(std::move(a)) {};
};


int main() {
  B b{A{}};
  return 0;
}

这一版代码修改了 B 的构造函数,让 a_ 通过移动构造函数来构造,同时修改了 main 中构造 b 的方式,改成通过一个临时的 A 对象来构造。

我预期会调用两次移动构造:一次从临时对象 A{} 构造 B(A a) 中的 a,第二次是构造 a_(std::move(a)) 中的 a_

结果,代码编译运行后的结果是:

A move ctor

不懂为什么。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment