gpt4 book ai didi

c++ - VS2010中的移动构造函数、非常量复制构造函数、列表的位置

转载 作者:行者123 更新时间:2023-11-30 04:36:41 24 4
gpt4 key购买 nike

我是移动构造函数的新手,对 VS2010 的行为很困惑。我设计了一个移动构造函数(A 类),据我所知,它是这样的:

A(A&& input) {some code}

当我使用列表的位置并放置类 A 的实例时:

mylist.emplace(a);

我的移动构造函数没有被调用,而是调用了一个非常量复制构造函数:

A(A& input) {the same code as move constructor}

另一方面,当我这样做时:

mylist.emplace(A(2));

我的移动构造函数被调用了。所以,我的问题是:

  1. 为什么 list 的 emplace 调用我的非常量复制构造函数而不是我的移动构造函数?
  2. 非 const 复制构造函数实际上是定义移动构造函数的另一种方法吗?
  3. 这种行为是正确的(对于 c++0x 编译器)还是只是 VS2010 的行为?

提前致谢。

最佳答案

mylist.emplace(a);

这里 a 是一个左值,因此它被复制而不是移动。您需要明确地移动它:

mylist.emplace(std::move(a));

是的,行为是正确的。

关于c++ - VS2010中的移动构造函数、非常量复制构造函数、列表的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4455093/

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