如何在C ++中默认初始化内置类型的局部变量? [英] How to default-initialize local variables of built-in types in C++?

查看:214
本文介绍了如何在C ++中默认初始化内置类型的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中默认初始化原始类型的局部变量?例如,如果a具有typedef:

How do I default-initialize a local variable of primitive type in C++? For example if a have a typedef:

typedef unsigned char boolean;//that's Microsoft RPC runtime typedef

我想更改以下行:

boolean variable = 0; //initialize to some value to ensure reproduceable behavior
retrieveValue( &variable ); // do actual job

进入可以自动默认初始化变量的东西-我不需要为其分配特定的值,但是我只需要在程序每次运行时将其初始化为相同的值-与可以在其中使用构造函数初始化器列表:

into something that would automagically default-initialize the variable - I don't need to assign a specific value to it, but instead I only need it to be intialized to the same value each time the program runs - the same stuff as with a constructor initializer list where I can have:

struct Struct {
   int Value;
   Struct() : Value() {}
};

每次绑定实例时,

Struct::Value都将默认初始化为相同的值,但是我从不在代码中写入实际值.

and the Struct::Value will be default-initialized to the same value every time an instance is cinstructed, but I never write the actual value in the code.

如何获取局部变量的相同行为?

How can I get the same behavior for local variables?

推荐答案

您可以通过以下方法模仿该行为:

You can emulate that behaviour by the following:

boolean x = boolean();

或更笼统的

T x = T();

如果存在这样的默认初始化,它将默认初始化x.但是,无论您做什么,仅编写T x都不会解决局部变量的问题.

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.

即使对于POD,您也可以使用placement-new来调用构造函数":

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

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

请注意,此代码会为非POD类型(尤其是具有非平凡析构函数的类型)产生未定义的行为.为了使此代码与用户定义的类型一起使用,我们首先需要调用对象的析构函数:

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();

此语法也可以 用于POD(由§§5.2.4/12.4.15保证),因此上述代码可以不加区别地用于 any 类型.

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.

这篇关于如何在C ++中默认初始化内置类型的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆