在类成员初始化中是否在编译时或运行时发生? [英] Does in class member initialization takes place at compile time or run-time?

查看:852
本文介绍了在类成员初始化中是否在编译时或运行时发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中引入了一个新功能,程序员可以在类的定义中初始化类成员变量,请参阅下面的代码:

In C++11 a new feature was introduced where the programmer can initialize class member variables inside class's definition, see code below:

struct foo
{ 
  int size = 3;
  int id   = 1;
  int type = 2;
  unsigned char data[3] = {'1', '2', '3'};
};

这个初始化是在编译期间发生的,或者这个特性只是语法糖和成员变量初始化默认构造函数?

Is this initialization takes place during compile time or this feature is just syntactic sugar and member variables are initialized in the default constructor?

推荐答案

首先是,如前所述,它是语法糖。但是,由于规则可能太多的记住,这里是一个逻辑实验,以帮助您找出在编译时会发生什么和

First of all yes, as stated before, it is syntactic sugar. But since the rules can be too much to remember, here's a logical experiment to help you figure out what happens in compile time and what not

你有你的c ++ 11类在类初始化器中的特性

You have your c++11 class that features in class initializers

struct foo { int size = 3; };

另一个类将帮助我们进行实验

And another class that will help us with our experiment

template<int N>
struct experiment { enum { val = N }; };

让我们的假设 H0 是在编译时发生初始化,我们可以写

Let our hypothesis H0 be that initialization does happen in compile time, then we could write

foo                a;
experiment<a.size> b;

没有运气,我们无法编译。可以认为失败是由于 foo :: size 是非常量所以让我们尝试

No luck, we fail to compile. One could argue that failure is due to foo::size being non constant so lets try with

struct foo { const int size = 3; }; // constexpr instead of const would fail as well

同样,gcc通知我们


'a'的值在常量表达式中不可用

the value of ‘a’ is not usable in a constant expression

p>

或(更清晰)visual studio 2013告诉我们

or (more clearly) visual studio 2013 tells us


错误C2975:'N':'example'无效的模板参数,期望的编译时常数表达式

error C2975: 'N' : invalid template argument for 'example', expected compile-time constant expression

必须舍弃 H0 并推断在编译时不会发生初始化

有一个旧的语法, p>

There is an old syntax that does the trick

struct foo { static const int size = 3; };

现在编译< a>但是要注意(技术上和逻辑上)在类初始化中不再是​​

Now this compiles but beware this is (technically and logically) no longer in class initialization.

我不得不撒谎一点点,但现在揭露真相:消息错误暗示 a 是真正的问题。你看,因为你有一个对象的实例(Daniel Frey也提到这个)内存(对于成员)必须初始化(在运行时)。如果最后一个例子中的成员是( const static ,那么它不是子对象的一部分(ny)类,你可以在编译时进行初始化。

I had to lie for a little to make a point, but to expose the whole truth now : Message errors imply that a is the real problem. You see, since you have an instance for an object (Daniel Frey also mentions this) memory (for members) has to be initialized (at runtime). If the member was (const) static, as in the final example, then it's not part of the subobjects of a(ny) class and you can have your initialization at compile time.

这篇关于在类成员初始化中是否在编译时或运行时发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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