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

标签 c++ c++11 move-semantics

考虑以下运行 C++11 的代码。如果我正确理解 move 语义,则不应调用复制构造函数。但它是。谁能解释一下为什么?

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

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并将其 move 到容器中。 A 的隐式生成的 move 构造函数被调用,需要构建基traced<A>来自临时对象的基础子对象。然而,trace显式声明一个复制构造函数,因此默认情况下它没有 move 构造函数,并且 A的 move 构造函数仍然需要为其基类子对象执行复制。

aList.emplace_back(6); 

这构建了一个 A直接放入容器中。不涉及任何类型的复制或 move 。

关于C++11 : Why is the copy ctor being called here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26321473/

相关文章:

c++ - 为什么会有注入(inject)的类名?

c++ - 将 cmake 与 Code::Blocks 一起使用

c++ - 如何将 QPlainText 中的文本方向更改为从右到左?

c++ - 在 C++0x lambda 中通过复制捕获引用变量

c++11 - C++ 为什么在 move 构造函数和 move 赋值运算符的上下文中需要 noexcept 来启用优化?

c++ - 用 boost::asio::io_service 替换 select()

android - 如何确定性地使用 std::this_thread::yield() ?

c++ - C++中的外部模板构造函数

c++ - 当源 obj 被销毁时,使用 move cstor 是否会丢失内存?

c++ - 三元运算符中的条件 move 或复制赋值