问题描述
例如,如果我有以下代码:
For example if I have the following code:
int main(){
myClass a(...);
a.doSomething();
if(...){
myClass c(...);
c.doSomething();
}
}
像gcc或clang这样的常规编译器是否会发现"a"在其生命周期内不再使用,而不是为"c"重新分配空间,而只是使用a的空间来优化这些变量的使用?如果该方法不适用于课堂,那么该方法是否适用于double或size_t之类的传统"类型?
Will usual compilers like gcc or clang optimize the using of these variables by finding out "a" will not be used anymore during it's lifetime and instead of reallocating space for "c", just use space of a? If that do not work for class, will that work for "traditional" type like double or size_t?
我正在尝试使经常调用的函数的分配成本最小化.但是在函数内部的某个地方,我觉得一些旧变量已经无用,但新变量不应称为该名称.编译器会直接为我重用变量还是应该做类似的事情
I'm trying to minimize the allocation cost of a frequently called function. But at somewhere inside the function I feel some old variables are already useless but new variables should not be called that name. Will compiler directly reuse variable for me or should I do something like
myClass a(...);
something(a);
if(...){
#define c a
c=myClass(...);
something c;
#undef c
}
推荐答案
通常,不允许编译器重用a
,直到其作用域的末尾为止,即作用域末尾的大括号}
.当析构函数执行某些特殊代码时,此功能(以可预见的时间销毁对象)可在C ++中提供防护.
Generally, the compiler is not allowed to reuse a
until the end of its scope, which is the closing brace }
at the end of the function. This feature (destroying objects at predictable time) enables making guards in C++, when destructor executes some special code.
由于分配自动变量的成本几乎为零,因此大部分成本用于调用构造函数.这不是您可以优化的东西.
Since allocating automatic variables costs virtually nothing, the majority of the cost is in calling the constructor. This is not something that you could optimize away.
如果您的对象具有琐碎的析构函数,则编译器可以重新使用内存.这样可以节省您的内存,而不是时间.
If your object has trivial destructor, the compiler could reuse the memory. This would save you memory, not time.
这篇关于编译器将优化并重用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!