C++11:为什么在这里调用复制ctor
C++11 : Why is the copy ctor being called here?
考虑下面运行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
。不涉及任何类型的复制或移动。
相关文章:
- 对复制 CTOR 和 CTOR 的未定义引用
- C++成功复制动态分配的 obj 而不复制 ctor?
- 给定一个右值,为什么移动ctor比常量复制ctor更匹配
- 在派生类中使用基类复制 CTOR
- 复制 CTOR 与赋值运算符以初始化对象(性能)
- 相同指令的输出不同 - 移动并复制CTOR
- 为什么编译器在调用 move 后选择复制 ctor
- 复制ctor被称为而不是移动ctor-可以编译器发出警告
- 复制 ctor 与互斥锁作为数据成员
- 为什么移动 ctor 比复制 ctor 慢?
- 是否可以使用 lambda 初始化变量(删除复制 ctor 时)
- 当使用三元运算符并删除移动/复制CTOR时,Visual Studio不执行RVO
- 警告在 std::move'ing 时调用复制 ctor
- 我无法弄清楚的复制 ctor 太多
- 如何在map中放置具有"deleted"复制ctor和赋值运算符的类?
- 当使用类型为"类&&"的变量作为参数时,为什么调用复制 ctor 而不是移动 ctor
- 以下内容中调用了复制ctor的次数
- 模板嵌套类的构造函数问题(复制 ctor 似乎覆盖了其他 ctor)
- 编译器提供复制 CTOR
- 有关一段带有模板、转换运算符和复制 ctor 的代码的问题