使用 const double 获取中间结果
我正在编写一个模拟程序,想知道在存储中间结果时使用 const double 是否有任何用处。考虑这个片段:
double DoSomeCalculation(const AcModel &model) {
(...)
const double V = model.GetVelocity();
const double m = model.GetMass();
const double cos_gamma = cos(model.GetFlightPathAngleRad());
(...)
return m*V*cos_gamma*Chi_dot;
}
请注意,该示例只是为了说明 - 从工程方面来看它可能没有多大意义。 在各种表达式中使用时代码变得更具可读性
cos_gamma
将例如 cos_gamma 存储在变量中的动机是,该余弦在 (...) 涵盖的其他表达式中多次使用,并且我觉得在使用而不是
cos(model.GetFlightPathAngleRad())
。现在实际的问题是:因为我希望余弦在整个代码部分中是相同的,并且我实际上仅将其创建为占位符,并且为了方便起见,我倾向于将其声明为 const。对于这种做法是好是坏,或者它最终是否会咬我有一个既定的意见吗?编译器是否使用了这些附加信息,或者我实际上是否阻碍了编译器执行有用的优化?
阿内
I a writing a Simulation program and wondering if the use of const double is of any use when storing intermediate results. Consider this snippet:
double DoSomeCalculation(const AcModel &model) {
(...)
const double V = model.GetVelocity();
const double m = model.GetMass();
const double cos_gamma = cos(model.GetFlightPathAngleRad());
(...)
return m*V*cos_gamma*Chi_dot;
}
Note that the sample is there only to illustrate -- it might not make to much sense from the engineering side of things. The motivation of storing for example cos_gamma in a variable is that this cosine is used many time in other expressions covered by (...) and I feel that the code gets more readable when using
cos_gamma
rather than
cos(model.GetFlightPathAngleRad())
in various expressions. Now the actual is question is this: since I expect the cosine to be the same througout the code section and I actually created the thing only as a placeholder and for convenience I tend to declare it const. Is there a etablished opinion on wether this is good or bad practive or whether it might bite me in the end? Does a compiler make any use of this additional information or am I actually hindering the compiler from performing useful optimizations?
Arne
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不确定优化部分,但我认为将其声明为 const 是很好的。这是因为,如果代码很大,那么如果有人在中间错误地执行了
cos_gamma = 1
,您将收到编译器错误,而不是运行时意外。I am not sure about the optimization part, but I think it is good to declare it as
const
. This is because if code is large, then if somebody incorrectly does acos_gamma = 1
in between you will get a compiler error instead of run time surprises.您只需计算一次余弦并在各处使用它,当然可以有所帮助。使结果
const
是确保您(或其他人)不会尝试在以后的某个地方更改它的好方法。这里的一个好的经验法则是首先使其正确且可读。不要担心编译器可能会或可能不会进行的任何优化。只有在分析并发现一段代码确实太慢之后,您才应该担心帮助编译器优化事情。
You can certainly help things by only computing the cosine once and using it everywhere. Making that result
const
is a great way to ensure you (or someone else) don't try to change it somewhere down the road.A good rule of thumb here is to make it correct and readable first. Don't worry about any optimizations the compiler might or might not make. Only after profiling and discovering that a piece of code is indeed too slow should you worry about helping the compiler optimize things.
鉴于您的代码:
我可能会保留 cos_gamma 不变。不过,我考虑将
V
和m
更改为引用:这样您就可以清楚地表明这些只是占位符。然而,它确实增加了生命周期问题的可能性——如果您使用引用,则显然必须确保它所引用的内容具有足够的生命周期。至少从表面上看,这可能不会成为问题。首先,
GetVelocity()
和GetMass()
可能返回值,而不是引用(在这种情况下,您将使用临时变量初始化引用,以及临时变量的生命周期)延长到它初始化的引用的生命周期)。其次,即使您返回实际引用,它显然也是模型的成员,(据猜测)无论如何,该引用都将存在于整个计算过程中。Given your code:
I would probably leave
cos_gamma
as it is. I'd consider changingV
andm
to references though:This way you're making it clear that these are strictly placeholders. It does, however, raise the possibility of lifetime issues -- if you use a reference, you clearly have to ensure that what it refers to has sufficient lifetime. At least from the looks of things, this probably won't be a problem though. First of all,
GetVelocity()
andGetMass()
probably return values, not references (in which case you're initializing the references with temporaries, and the lifetime of the temporary is extended to the lifetime of the reference it initializes). Second, even if you return an actual reference, it's apparently to a member of themodel
, which (at a guess) will exist throughout the entire calculation in question anyway.我希望我能使用更多这样编写的代码!
任何可以让代码更具可读性的事情都是一件好事。仅在需要优化时才进行优化。
我对 C++ 最大的不满是默认值不是 const。自由使用
const
让你的脚不被弹孔!I wish I worked with more code written like this!
Anything you can do to make your code more readable can only be a good thing. Optimize only when you need to optimize.
My biggest beef with C++ is that values are not
const
by default. Useconst
liberally and keep your feet bullet-hole free!编译器是否利用这一点是一个有趣的问题 - 一旦您处于优化完全工作的程序的阶段。在那之前,您编写程序主要是为了后来必须查看代码的人类。编译器会很高兴地吞下(客观上)非常不可读的代码,缺少空格、换行符和滑稽的缩进。人类不会。
最重要的问题是,代码的可读性如何,以及更改代码是否容易出错。在这里,
const
提供了巨大的帮助,因为它会让编译器对每个错误地更改了不应该更改的内容的人咆哮。我总是把所有东西都设为常量,除非我真的非常希望它是可变的。Whether the compiler makes use of this is an interesting question - once you're at the stage of optimizing a fully working program. Until then, you write the program mostly for the humans coming later and having to look at the code. The compiler will happily swallow (objectively) very unreadable code, lacking spaces, newlines, and sporting hilarious indentation. Humans won't.
The most important question is, how readable is the code, and how easy it is to make a mistake changing it. Here,
const
helps tremendously, because it makes the compiler bark at everyone who mistakenly changes anything that shouldn't change. I always make everythingconst
unless I really, really want it to be changeable.