场景是想确定什么时候调用移动构造函数,参考链接有解释

  • X does not have a user-declared copy constructor,

  • X does not have a user-declared copy assignment operator,
  • X does not have a user-declared move assignment operator,
  • X does not have a user-declared destructor, and
  • the move constructor would not be implicitly defined as deleted.

比如下面这段代码

#include <iostream>
#include <tuple>

struct A{
A(){std::cout<<"ctor\n";}
};

int main()
{
   A a;
   A b(std::move(a));
}

无法判断

#include <iostream>
#include <tuple>

struct A{
A(){std::cout<<"ctor\n";}
A(const A& a)=delete;//{std::ignore = a; std::cout<<"copy"<<'\n';}
};

int main(){
   A a;
   A b(std::move(a));
}

这样会提示

prog.cc: In function 'int main()':
prog.cc:15:20: error: use of deleted function 'A::A(const A&)'
    A b(std::move(a));
                    ^
prog.cc:7:1: note: declared here
 A(const A& a)=delete;//{std::ignore = a; std::cout<<"copy"<<'\n';}

当有析构的时候也无法生成move ctor,比如

#include <iostream>
#include <tuple>
#include <memory>
struct A{
A(int a=0):a_(std::make_unique<int>(a)){std::cout<<"ctor\n";}
//A(const A& a)=delete;//{std::ignore = a; std::cout<<"copy"<<'\n';}
//A(A&& a){std::ignore = a; std::cout<<"move"<<'\n';}
~A(){std::cout<<"dtor\n";}
std::unique_ptr<int> a_;
};

int main()
{
   A a;
   A b(std::move(a));
}
/*
prog.cc:16:20: error: use of deleted function 'A::A(const A&)'
    A b(std::move(a));
                    ^
prog.cc:5:8: note: 'A::A(const A&)' is implicitly deleted because the default definition would be ill-formed:
 struct A{
        ^
prog.cc:5:8: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
In file included from /opt/wandbox/gcc-5.4.0/include/c++/5.4.0/memory:81:0,
                 from prog.cc:4:
/opt/wandbox/gcc-5.4.0/include/c++/5.4.0/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
*/

由于有dtor,没有默认生成move ctor,而是生成了copy ctor,而unique_ptr的copy ctor是删除的导致错误

如何捕捉编译器调用了什么构造函数?有没有例外情况?

貌似汇编能看出来https://godbolt.org/z/Nn4iod


ref

  1. https://zh.cppreference.com/w/cpp/language/move_constructor
  2. https://stackoverflow.com/questions/8283589/are-move-constructors-produced-automatically