如何使用Type()(例如语法)来初始化Type *指针的值? [英] How do I value-initialize a Type* pointer using Type()-like syntax?

查看:191
本文介绍了如何使用Type()(例如语法)来初始化Type *指针的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内置类型的变量可以像下面这样进行值初始化:

  int var = int 

这样我得到默认值 int



但是如果我尝试对指针做类似的事情:

  int * ptr = int *(); (Visual C ++ 10)拒绝编译( type int(code))



如何使用Type()初始化一个Type *指针 - 例如语法?


$


< b
$ b

你不能。语法 T()在5.2.3 / 1,2(C ++ 03,C ++ 11 FDIS中略有不同的措辞)中定义。特别是第二段说明:


表达式T(),其中T是一个简单类型说明符非数组完整对象类型或(可能是cv限定的)void类型,创建一个指定类型的值,它是值初始化的(8.5);


这意味着 int()将创建类型为int和 value-initialize 的右值。现在的问题是 int * 不是一个简单类型说明符,而是一个详细说明类型说明符。语法中simple-type-specifier的定义是:

  simple-type-specifier:
:: opt nested-name-specifieropt type-name
:: opt nested-name-specifier template-id
char
wchar_t
bool
short
int
long
signed
unsigned
float
double
void

类型名称定义为:

  type-name:
class- name
enum-name
typedef-name

解决方案工作。 typedef的创建(直接或通过模板)创建一个类型名(第三种类型),可以用作简单类型说明符(第一种类型)。


Variables of built-in types can be value-initialized like this:

int var = int();

this way I get the default value of int without hardcoding the zero in my code.

However if I try to do similar stuff for a pointer:

int* ptr = int*();

the compiler (Visual C++ 10) refuses to compile that (says type int unexpected).

How do I value-initialize a pointer in similar manner?

解决方案

How do I value-initialize a Type* pointer using Type()-like syntax?

You cannot. The syntax T() is defined in 5.2.3/1,2 (C++03, slightly different wording in C++11 FDIS). In particular the second paragraph states:

The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized (8.5);

That means that int(), will create an rvalue of type int and value-initialize it. Now the problem is that int* is not a simple-type-specifier, but rather an elaborated-type-specifier. The definition of simple-type-specifier in the grammar is:

  simple-type-specifier:
    ::opt nested-name-specifieropt type-name
    ::opt nested-name-specifier template template-id
    char
    wchar_t
    bool
    short
    int
    long
    signed
    unsigned
    float
    double
    void

With type-name being defined as:

  type-name:
    class-name
    enum-name
    typedef-name

This is what makes the proposed solutions work. The creation of the typedef (either directly or through the template) creates a type-name (third type) that can be used as a simple-type-specifier (first type).

这篇关于如何使用Type()(例如语法)来初始化Type *指针的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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