C ++ Copy Constructor

I have a question about this syntax regarding initialization.

Quote from 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
}

Case 1:
After changing the from const parameter to non const in the copy constructor, case 1 will not compile, as expected, from Wikipedia. However, when launched using the appropriate copy constructor, it only calls the default constructor. Why doesn't it also call the copy constructor? Is this compile-time optimization?

Case 2: The
answer to case 1 will probably answer case 2 for me, but why does it only call the copy constructor once?

+3
source share
2 answers
Foo b = Foo();

, . , , .

, , Foo() , . const ( c-tor), , const.

+4

X() , const ( MSVS , ).

1) ,

2) , a . , , , .

+1

All Articles