Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird c++ code snippet

Tags:

c++

I have this snippet:

template<class T>
class VECTOR_2D 
{
public:
    T x,y;

    VECTOR_2D() 
        :x(T()),y(T())
    {}
}

What are x and y initialized to in the constructor?

like image 964
thikonom Avatar asked Dec 16 '22 14:12

thikonom


1 Answers

x and y are copy-initialized to T's value-initialized value.

From the C++03 standard, §8.5/7:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

And from §8.5/5:

To value-initialize an object of type T means:

  • if T is a class type with a user-declared constructor, then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized

To zero-initialize an object of type T means:

  • if T is a scalar type, the object is set to the value of 0 (zero) converted to T;
  • if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;
  • if T is a union type, the object’s first named data member) is zero-initialized;
  • if T is an array type, each element is zero-initialized;
  • if T is a reference type, no initialization is performed.

x(T()),y(T()) could be replaced with x(),y() to instead value-initialize x and y directly. In most circumstances this will achieve the same net effect (assuming T is copy constructable), but in some cases this will be more efficient, so as a general rule this approach should always be preferred.

like image 168
ildjarn Avatar answered Jan 01 '23 09:01

ildjarn