【发布时间】:2018-07-16 15:15:10
【问题描述】:
我最近开始使用 c++ 并选择学习 c++11 功能。 但是 c++ 代码的运行方式有时并不那么具体。
下面是我的代码。
在decltype(std::move(sample)) sample2 = std::move(sample); 的部分,我不确定为什么这条线不调用移动构造函数。
你能解释一下为什么吗?
#include <iostream>
class AAA
{
public:
AAA() { std::cout << "default constructor" << std::endl; }
AAA(const AAA& cs) { std::cout << "copy constructor" << std::endl; }
AAA(AAA&& cs) { std::cout << "move constructor" << std::endl; }
~AAA() { std::cout << "destructor" << std::endl; }
};
int main(int argc, char* args[])
{
AAA sample;
// ((right here))
decltype(std::move(sample)) sample2 = std::move(sample);
return 0;
}
它是在 [ubuntu 16.04 LTS] 上用 [gcc 5.4.0] 编译的
【问题讨论】:
-
@user202729 很确定
= std::move(sample)与decltype无关 -
那行是
AAA&& sample2 = std::move(sample);,它不应该比AAA& sample2 = sample;更能引起构造。 -
@FrançoisAndrieux 这应该是一个答案
-
@user202729 感谢您的建议
-
@KiseongYoo 你应该知道允许临时对象绑定到
const T &的语言中的一个例外,这在某些情况下可以延长临时对象的生命周期。见this question。
标签: c++ c++11 move-semantics decltype stdmove