How to default-initialize local variables of built-in types in C++?

旧时模样 提交于 2019-12-01 00:18:06

You can emulate that behaviour by the following:

boolean x = boolean();

or, more general,

T x = T();

This will default-initialize x if such a default-initialization exists. However, just writing T x will never do the trick for local variables, no matter what you do.

You can also use placement-new to invoke a “constructor”, even for POD:

T x;
new (&x) T();

Notice that this code produces undefined behaviour for non-POD types (in particular for types that have a non-trivial destructor). To make this code work with user-defined types, we first need to call the object’s destructor:

T x;
x.~T();
new (&x) T();

This syntax can also be used for PODs (guaranteed by §§5.2.4/12.4.15) so the above code can be used indiscriminately for any type.

    int var = int();
    string str = string();
    ...

...or whatever typename you want.

You could provide a wrapper that behaves as the underlying type through overloaded conversion operators.

#include <cassert>

template <class T>
class Type
{
    T t;
public:
    Type(const T& t = T()): t(t) {}
    operator T&() { return t; }
    operator const T&() const { return t; }
};

int main()
{
    Type<unsigned char> some_value;
    assert(some_value == '\0');
}

This should be a rather OK usage for conversion operators.

Wrapping in the struct (Boolean) as in your example and accessing via a public member (Boolean::value). It may not be the most elegant solution (some cruft for small benefit), but it similar to what you already showed.

If I understand the original question, the poster is saying he wants variables of a given type to always have the same initial value, but he doesn't care what that value is, because he'll never look at it. Am I right?

If so, then my question for the poster is this: If you did not initialize the variables they would have random initial values... but you said you never look at initial values - so why does it matter if they're random?

I think the key question is - what are you trying to achieve here?

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