我对这个关于初始化的语法有疑问。
引自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,但是为什么这只会调用一次复制构造函数呢?