C++11:为什么在这里调用复制ctor

C++11 : Why is the copy ctor being called here?

本文关键字:复制 ctor 调用 在这里 为什么 C++11      更新时间:2023-10-16

考虑下面运行C++11的代码。如果我正确理解了移动语义,就不应该调用复制构造函数。但事实确实如此。有人能解释一下原因吗?

template<class D>
struct traced
{
public:
  traced() = default;
  traced(traced const&) { std::cout << typeid(D).name() << " copy ctorn"; }
protected:
  ~traced() = default;
};

class A : public traced<A>{
public:
  A(int x) : x_(x) {}
private:
  int x_;
};
int main() {
  // I thought the following two are equivalent. Apparently not.
  aList.push_back(A(6)); // Prints out ".. copy ctor" ..
  aList.emplace_back(6); // Does not print out " ... copy ctor"
}
aList.push_back(A(6));

这将构造一个临时A并将其移动到容器中。调用了隐式生成的A的移动构造函数,该构造函数需要从临时的基子对象构造基traced<A>。然而,trace显式声明了一个复制构造函数,因此默认情况下它没有移动构造函数,而A的移动构造函数仍然需要为其基类子对象执行复制。

aList.emplace_back(6); 

这将直接在容器中构造一个A。不涉及任何类型的复制或移动。