C++代码中custom类构造函数的调用次数与顺序确认
你的判断完全正确,在主流编译器默认配置、或C++17及更高版本标准下,构造函数的调用次数和顺序和你说的一致。
分析过程
先给出相关代码回顾:
struct custom { custom(); custom(const custom &); custom(custom &&); }; custom find() { return custom(); } void take(const custom &c) { custom temp = c; } void take(custom &&c) { custom temp = std::move(c); }
我们逐行拆解执行逻辑:
- 执行
custom first = find();
C++17起强制要求返回值优化(RVO),低版本编译器也默认开启该优化,find内返回的临时对象会直接构造在first的内存空间上,只会触发1次默认构造函数,没有额外的拷贝/移动开销。 - 执行
take(first);first是左值,匹配take(const custom &)重载,函数内用左值引用c拷贝构造temp,触发1次拷贝构造函数。 - 执行
custom second = find();
和first的构造逻辑完全一致,触发1次默认构造函数。 - 执行
take(std::move(second));std::move将second转为右值,匹配take(custom &&)重载,函数内用右值引用c移动构造temp,触发1次移动构造函数。
总共有4次构造函数调用,顺序为:默认构造 → 拷贝构造 → 默认构造 → 移动构造。
特殊情况说明
如果手动关闭编译器的返回值优化(比如GCC/Clang加-fno-elide-constructors编译参数),那么每次find调用还会额外产生两次移动构造(函数内临时对象移动构造返回值临时,返回值临时再移动构造first/second),但这属于非默认的特殊场景,常规开发中不会遇到。
内容的提问来源于stack exchange,提问作者user5965026
相关产品推荐
相关产品推荐

