0

In my code i have ints, bools, pointers and so on, i also have some type defined by me with typedef, how can i manage the default value initialization like it happens in the objects with the contrunctor?

I want to be sure that

T var;

if untouched, is always equal to my default value and i like to do this without parsing each line of code anche changing the default value manually and without using a preprocessor macro.

is this possible? for a new typedef is possible to define a default value?

4

3 回答 3

6

In C++11, you could write T var{}; to get value initialization to the default value.

In C++03, you could write a non-POD wrapper, whose default constructor will get called by T var;:

template<class T>
struct default_initializer{
  default_initializer() : value() {}
  default_initializer(T const& v) : value(v) {}
  T value;
};

// somewhere in code
default_initializer<T> var; // calls default ctor and initializes 'value'
                            // to its default value

This will allow you to safely default initialize even primitive , POD and aggregate types, which are normally left uninitialized by the T var; declaration.

于 2012-07-15T16:45:16.330 回答
3

This is not possible for primitive types since they don't have a constructor. primitive types which are declared in the context of a function scope are not initialized by default and contain garbage. primitive variables which are declared in the global scope as global variables are always initialized to 0.

于 2012-07-15T16:42:46.347 回答
0

There is no way to achieve this for ints, bools, pointers and other primitive data types without having to write some additional code whenever you declare values of such types. But for instances of your custom classes, there is.

于 2012-07-15T16:56:23.177 回答