gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:55 26 4
gpt4 key购买 nike

考虑以下运行 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com