0

I wrote a simple code like this:

class Test
{
public:
    Test()
    {
        cout << "Constructor called." << endl;
    }

    ~Test()
    {
        cout << "Destructor called." << endl;
    }

    Test(const Test& test)
    {
        cout << "Copy constructor called." << endl;
    }

    void Show() const
    {
        cout << "Show something..." << endl;
    }
};

Test Create()
{
    return Test();
}

int main()
{
    Create().Show();
}

The output for this code are:

Constructor called.
Show something...
Destructor called.

But when I modified the function Create() like this:

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

The output are:

Constructor called.
Copy constructor called.
Destructor called.
Show something...
Destructor called.

Why the anonymous object do not call the copy constructor and destructor?Please help me, thanks.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
TwenteMaster
  • 148
  • 2
  • 12

1 Answers1

2

This is called copy elision. In both cases copy elision is permitted; for some reason your compiler does it in the first case but not in the second case. (MSVC in debug mode apparently decides to not do it sometimes).

Note, when you say "anonymous class", you mean temporary object. "Anonymous class" means something different.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365