【问题标题】:Shouldn't this code compile according to 12.8p2 in the Standard?这段代码不应该按照标准中的 12.8p2 编译吗?
【发布时间】:2013-06-20 03:57:08
【问题描述】:

此代码在 VS2010 中无法编译。它发出错误 C2440: 'argument' : cannot convert from 'A' to 'A &',但根据标准中的 12.8p2,A::A(A&) 是有效的复制构造函数,a 是表达式 @987654325 中的左值@在main().

#include <iostream>

class A
{
    public:

    int x;
    A(int a) { x = a; std::cout << "Constructor\n"; }
    A(A& other) { x = other.x; std::cout << "Copy ctor\n"; }
    A(A&& other) { x = other.x; other.x = 0; std::cout << "Move ctor\n"; }
};

A foo(A a) 
{
    return a;
}

int main(void)
{
    A a(5);
    A b = foo(a);
}

【问题讨论】:

  • 在 GCC 4.7.2 中编译并运行良好。
  • 它是否调用 move ctor,将返回值从 foo() 复制到 b?
  • 是的,请看这里:ideone.com/Ykwm2Z
  • This site 在 VS 2012 CTP 上编译代码很好,所以这可能是 VS2010 的错误。
  • 在我的 VC2010 Ultimate 版本 10.0.40219 SP1Rel 和 VC++ 版本 16.00.40219.01 的副本上编译良好​​span>

标签: c++ copy-constructor


【解决方案1】:

我会说这取决于您所谈论的标准。假设 C++11,那么我的看法是它应该没问题并且应该产生以下结果:

Constructor  <- Construction of 'a' in main
Copy ctor    <- Construction of 'a' in foo
Move ctor    <- Move from foo's return value into b

正如您指出的那样,传递给 foo 的 a 是一个左值。但是, foo 的返回值是一个右值,因此应该在 C++11 之前的情况下调用 const A& 复制构造函数(不存在),或者在 C++11 的情况下调用移动构造函数。

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 2015-12-02
    • 2018-08-20
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多