-1

Suppose I have a class here:

class Test
{
    Test(int x, const char* y)
    {
        // Do something
    }
}

and I wanted to initialize it. I have 2 methods:

Test test(100, "hello world!");

and

Test test = Test(100, "hello 2nd method!");

What are the differences between the 2 and which one is better ( as in faster )

I saw this question here, but it is for implicit converting the objects.

  • 1
    But the question you've linked to does cover this. There's no implicit conversions in that question either. – cigien Nov 13 '20 at 21:34

1 Answers1

0

It depends.

In old compilers, the statement Test test = Test(100, "hello 2nd method!"); would first create a temporary Test object using your converting constructor, and would then use the copy constructor to create the test object to make a copy of that temporary.

In modern compilers, there is no difference whatsoever between these two statements. The temporary is optimized away by the compiler (see Copy Elision) so that the statement Test test = Test(100, "hello 2nd method!"); does the exact same thing as the statement Test test(100, "hello world!");. There is no temporary created anymore.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770