0

I am currently re-engineering a colleague's code. I foudn that he often uses the syntax like

double a(anotherDouble);  --- A

instead of

double a = anotherDouble;  --- B

I am wondering if his syntax faster, maybe method A can save a constructor operation?

can someone give a little bit insight here?

thanks and have a nice holiday season!

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
James Bond
  • 7,533
  • 19
  • 50
  • 64

4 Answers4

1

For the inbuilt datatype double they both are same, theres no performance difference.

In case of custom classes.
First is Direct Initialization while second is called Copy Initialization.

Good Read:

Is there a difference between copy initialization and direct-initialization

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

For a double (or some predefined type), that should not matter. I find double pi=3.14; more readable than double pi(3.14); but it is a matter of taste.

For a user defined class C, writing C x = C(3); may involve a constructor for initialization and another for copying, but sometimes it is optimized by the compiler.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

There is no assignment operator invoked at all in this. A a = b; always invokes a constructor. If b is of object of type A, copy-constructor invoked. If b is object of some other type B, then suitable constructor invoked, such as A( const B& ). In any circumstances, A a(b); and A a = b; will result in absolutely the same code with the same constructor called once.

The following will NOT compile, since there is no suitable constructor, even though there is suitable assignment operator and default constructor for class TB:

#include <iostream>    

class TA
{
 public:
  TA()
  {
   std::cout << "TA()" << std::endl;
  }
  TA( const TA& )
  {
   std::cout << "TA(const TA&)" << std::endl;
  }
};

class TB
{
 public:
  TB()
  {
   std::cout << "TB()" << std::endl;
  }
  TB( const TB& )
  {
   std::cout << "TB(const TB&)" << std::endl;
  }
  TB& operator=( const TA& )
  {
   std::cout << "TB& operator=( const TA& )" << std::endl;
   return ( *this );
  }

};

int main( void )
{
 TA la;
 TB lb = la;

 return ( 0 );
}

So the answer to your question is "No, it's not faster, it's 100% the same".

lapk
  • 3,838
  • 1
  • 23
  • 28
0

double is not a class to start with. But anyway, I have never seen a compiler that generates different code for these two constructs, even with classes, they generate equivalent code, and the standard states that explicitly.

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49