Initialize all the variables of a specific type to a specific default value in C++

强颜欢笑 提交于 2019-12-12 04:08:42

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/11493701/initialize-all-the-variables-of-a-specific-type-to-a-specific-default-value-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!