初始化列表和优化 [英] Initialization lists and optimization

查看:68
本文介绍了初始化列表和优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


struct S

{

int x;

S( int y):x(y){} // 1

S(int y){x = y; } // 2

}


编译器可能适用的代码优化是否有1~2之间的差异?


祝你好运,

Marcin

解决方案

Marcin Kalicinski发布:

大家好,

结构S
{
int x;
S(int y): x(y){} // 1
S(int y){x = y; } // 2


对于编译器可能适用的代码优化,1和2之间有什么区别吗?

祝你好运,
Marcin



我不知道。我相信我们拥有第一个

表单的唯一原因是初始化const对象和引用,例如。


struct S

{

const int x;

S(int y):x(y){} // 1

S(int y){x = y} // 2编译错误

};

至于一个比另一个更有效率,我想不出任何理由<我最喜欢的是


-JKop




" JKop" ; < NU ** @ NULL.NULL>在消息中写道

新闻:XS ***************** @ news.indigo.ie ...

Marcin Kalicinski发表:

大家好,

结构S
{
int x;
S(int y):x (y){} // 1
S(int y){x = y; } // 2


对于编译器可能适用的代码优化
,1和2之间是否存在差异?



[snip]

至于一个比另一个更有效的人,我无法想到任何
的理由。


< br $>
写作:


S :: S(int y){x = y; }


实际上处理为:


S :: S(int y):x(){x = y; }


所以你是默认(或者它是值)初始化,然后分配一个值。

哪个效率低于:


S :: S(int y):x(y){}

Jeff F




" JKop" < NU ** @ NULL.NULL>在消息中写道

新闻:XS ***************** @ news.indigo.ie ...

对于一个比另一个更有效率的人,我无法想到任何
的理由。




常见问题解决这个问题
http:// www.parashift.com/c++-faq-lit....html#faq-10.6


问候,

Sumit。


Hi all,

struct S
{
int x;
S(int y): x(y) { } // 1
S(int y) { x = y; } // 2
}

Is there any difference between 1 and 2 regarding code optimizations that
the compiler may apply?

Best regards,
Marcin

解决方案

Marcin Kalicinski posted:

Hi all,

struct S
{
int x;
S(int y): x(y) { } // 1
S(int y) { x = y; } // 2
}

Is there any difference between 1 and 2 regarding code optimizations that
the compiler may apply?

Best regards,
Marcin


Not of which I am aware. I believe the sole reason that we have the first
form is for the initialization of const objects and references, eg.

struct S
{
const int x;
S(int y) : x(y) { } //1
S(int y) { x = y } //2 Compile ERROR
};
As for one being more efficient than the other, I can''t think of any reason
off the top of my head.
-JKop



"JKop" <NU**@NULL.NULL> wrote in message
news:XS*****************@news.indigo.ie...

Marcin Kalicinski posted:

Hi all,

struct S
{
int x;
S(int y): x(y) { } // 1
S(int y) { x = y; } // 2
}

Is there any difference between 1 and 2 regarding code optimizations that the compiler may apply?


[snip]
As for one being more efficient than the other, I can''t think of any reason off the top of my head.



Writing:

S::S( int y ){ x = y; }

Actually is processed as:

S::S( int y ):x(){ x = y; }

So you are default(or is it value) initializing, then assigning a value.
Which is less efficient than:

S::S( int y ):x(y){}

Jeff F



"JKop" <NU**@NULL.NULL> wrote in message
news:XS*****************@news.indigo.ie...

As for one being more efficient than the other, I can''t think of any reason off the top of my head.



The FAQ addresses this
http://www.parashift.com/c++-faq-lit....html#faq-10.6

Regards,
Sumit.


这篇关于初始化列表和优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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