8

このコードは VS2010 ではコンパイルできません。エラー C2440: 'argument' : cannot convert from 'A' to 'A &' が発生しますが、標準の 12.8p2 によれば、A::A(A&)は有効なコピー コンストラクターであり、式inaの左辺値です。A b = foo(a);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);
}
4

1 に答える 1

2

それはあなたが話している基準に依存すると思います。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 の場合は move コンストラクターを呼び出す必要があります。

于 2013-06-24T20:49:42.367 に答える