<分区>
我有以下类(class)
class widget {
// The methods only print their name, i.e. c'tor, destructor etc.
public:
widget();
widget(const widget&);
widget(widget&&);
~widget();
auto operator=(const widget&) -> widget&;
auto operator=(widget&&) -> widget&;
};
我在下面的代码中使用
#include "widget.h"
auto main() -> int {
widget c(std::move(widget()));
c = std::move(widget());
return 0;
};
由此产生的行为对我来说是可以理解的。在第一次调用中构造一个小部件,然后调用 move 构造函数并在临时小部件上调用析构函数。
第二个调用做同样的事情,期望调用 move 赋值运算符而不是 move 构造函数。
离开 main 方法,在 c
上调用析构函数。
现在是有趣的部分:
#include "widget.h"
auto main() -> int {
widget c((widget()));
c = widget();
return 0;
};
如果我省略了对 std::move
的调用,第一种情况将停止工作并导致仅调用一次构造函数。而第二个案例仍然像以前一样工作。
我在这里错过了什么?为什么这两个函数调用以不同方式处理它们的参数? 我在 gcc 和 clang 上试过了。