我有一个关于这个语法有关初始化的问题。C++复制构造函数
从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引用:
一旦在拷贝构造函数改变从常量的参数非常量,从维基百科预期的情况下1将无法编译。但是,当使用正确的拷贝构造函数运行时,它只会调用默认的构造函数。为什么它不会调用复制构造函数?这是在编译时完成的优化吗?
案例2:
案例1的答案可能会为我回答案例2,但为什么这只会调用一次复制构造函数?
“*这是在编译时完成的优化吗?*”它被称为[_copy elision_](http://en.wikipedia.org/wiki/Copy_elision) - 请仔细阅读。 : - ] – ildjarn