0

Take a look at the following code:

class Test
{
public:
    Test()
    {
        cout << "default\n";
    }

    Test(const Test&)
    {
        cout << "copy\n";
    }

    Test& operator = (const Test&)
    {
        cout << "assign\n";
        return *this;
    }
};

int main()
{
    Test t = Test();
}

Which constructor should be called in the main function?

I run and it prints "default" and nothing else. However, if I make the copy constructor and assignment operator private, it doesn't compile. But it wasn't using that constructor any way.

Which constructor should be used? Is it guaranteed by standard? Is this some rule I didn't know about?

Live code examples:

http://ideone.com/lnUEA1

http://ideone.com/nXjAo4

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • 3
    See [*copy elision*](http://en.cppreference.com/w/cpp/language/copy_elision). – juanchopanza Jul 01 '14 at 12:19
  • Compilers do _stuffs_ in behind – P0W Jul 01 '14 at 12:19
  • I thought this would violate "as-if" rule but I see there is special exception granted. – Neil Kirk Jul 01 '14 at 12:20
  • I guess, the question is "Why do we still need copy-constructor with copy elision ?" - "Just because your program doesn't end up actually invoking the copy constructor does not mean it is permissible to omit it."(http://stackoverflow.com/questions/15972478/why-the-error-c2248-when-the-copy-constructor-is-private-in-the-code-below) And - "There are some cases where the optimization won't actually kick in." (http://msdn.microsoft.com/en-us/library/ms364057%28v=vs.80%29.aspx) – SChepurin Jul 01 '14 at 12:45

1 Answers1

1

Compilers are free to optimize out unnecessary copies. That doesn't mean an accessible copy constructor isn't needed.

Your code show copy initialization, which means a copy constructor must be available. Theoretically, the default and copy constructor would be called.

The assignment operator isn't needed or used.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625