c++typesconventionbuilt-in-types

Primitive built-in types initialization


I am a bit confused about how to initialize a built-in type like an int or a double. I am talking about copy initialization and direct initialization :

int a = 0; // copy initialization
int b(0);  // direct initialization 

What are the best practices ? Is direct initialization available for all C++ versions ?


Solution

  • "best practice" is probably not something that can be clearly stated - some people prefer one, some the other, and modern compilers should do the same thing for both unless your constructor for empty object does stuff the compiler can't eliminate. For basic types that the compiler knows natively, the code generated should turn out identical [possibly SOME compilers make subtle differences because the code takes a different path or some such, so code-generation is in a subtly different order, leading to different sets of optimisation or different register allocation, etc, but generally I'd be disappointed if there is any measurable difference]

    I'm not aware of a version of C++ that doesn't support both for simple types. Obviously, for classes and other complex objects, it's somewhat dependent on what constructors and such are available.