初期化に関するこの構文について質問があります。
http://en.wikipedia.org/wiki/Copy_constructorから引用
X a = X();
// valid given X(const X& copy_from_me) but not valid given X(X& copy_from_me)
// because the second wants a non-const X&
// to create a, the compiler first creates a temporary by invoking the default constructor
// of X, then uses the copy constructor to initialize a as a copy of that temporary.
// However, for some compilers both the first and the second actually work.
#include <iostream>
class Foo
{
public:
Foo()
{
std::cout << "Default Constructor called" << std::endl;
}
Foo(const Foo& other)
{
std::cout << "Copy constructor called" << std::endl;
}
Foo& operator=(const Foo& rhs)
{
std::cout << "Assignment operator called" << std::endl;
}
};
int main()
{
Foo b = Foo(); //case 1:default
Foo c = Foo(a); //case 2: copy constructor
}
ケース 1:
コピー コンストラクターでパラメーターを const から非 const に変更すると、ケース 1 はウィキペディアの期待どおりにコンパイルされません。ただし、適切なコピー コンストラクターを使用して実行すると、既定のコンストラクターのみが呼び出されます。コピーコンストラクターも呼び出さないのはなぜですか? これはコンパイル時に行われる最適化ですか?
ケース 2:
ケース 1 の答えはおそらくケース 2 の答えになるでしょうが、なぜこれはコピー コンストラクターを一度だけ呼び出すのでしょうか?