1

There is a part of C++ code I don't really understand. Also I don't know where should I go to search information about it, so I decided to ask a question.

#include <iostream>
#include <string>

using namespace std;

class Test
{
    public:
        Test();
        Test(Test const & src);
        Test& operator=(const Test& rhs);
        Test test();
        int x;
};

Test::Test()
{
    cout << "Constructor has been called" << endl;
}

Test::Test(Test const & src)
{
    cout << "Copy constructor has been called" << endl;
}

Test& Test::operator=(const Test& rhs)
{
    cout << "Assignment operator" << endl;
}

Test Test::test()
{
    return Test();
}

int main()
{
    Test a;
    Test b = a.test();

    return 0;
}

Why the input I get is

Constructor has been called
Constructor has been called

? a.test() creates a new instance by calling "Test()" so that's why the second message is displayed. But why no copy constructor or assignment called? And if I change "return Test()" to "return *(new Test())" then the copy constructor is called.

So why isn't it called the first time?

user2452103
  • 199
  • 5
  • The assignment-operator is not called because there's no assignment in `Test b = a.test();`. It's copy-initialization. – dyp Jan 01 '14 at 23:05
  • @DyP: `But why no copy constructor or assignment called?` – Lightness Races in Orbit Jan 01 '14 at 23:22
  • @LightnessRacesinOrbit ? (of course the copy-ctor isn't called due to copy elision; I just wanted to point out that even though it looks like assignment, it is no assignment) – dyp Jan 01 '14 at 23:29

2 Answers2

3

Compilers are very smart. Both copies - returning from test and initialising b (not this is not an assignment) - are elided according to the following rule (C++11 §12.8):

when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

Compilers are allowed to do this even if it would change the behaviour of your program (like removing your output messages). It's expected that you do not write copy/move constructors and assignment operators that have other side effects.

Note that is only one of four cases in which copy elision can occur (not counting the as-if rule).

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
-2

The call to a.test() returns by value and this value is then assigned to b "copying" the return value. This invokes the copy constructor.

TimDave
  • 652
  • 3
  • 6