[英]How many ways of generating temporary objects/needlessly invoking constructor are there?
Temporary objects/wasteful objects can be a big bottleneck for ultra-low latency applications. 临时对象/垃圾对象可能是超低延迟应用程序的一大瓶颈。 I am trying to make myself aware of the pitfalls of needlessly invoking a constructor, so I wanted to know if there are any ways I am unware of.
我试图使自己意识到不必要调用构造函数的陷阱,所以我想知道是否有我不知道的方法。 I am aware of the following ways when the constructor is "silently" called:
当“无声地”调用构造函数时,我知道以下几种方式:
1) 1)
//a temporary "object" is created when adding x and y and then assigned to z
int x,y,z;
z = x + y;
2) 2)
//A temporary object is created here when the return value is passed. Its also possible
//another temporary object is created during the assignment?
A a = my_function();
A my_function(){
return new A();
}
3) 3)
A a = my_function();
A my_function(){
A a;
return a;
}
4) Where arguments are passed in by value 4)参数通过值传递
A a;
my_function(a);
void my_function(A a){
}
5) Not using initialiser lists: 5)不使用初始化程序列表:
class A{
B b;
C c;
A(B bb, C cc):
{
this.b = bb;
this.c = cc;
}
}
Are there any other examples where constructors are implicitly called? 还有其他示例隐式调用构造函数吗?
A a = A();
(a simpler case of your function example), though I believe most compilers these days optimize that to direct initialization. (您的函数示例的一个简单案例),尽管我相信如今大多数编译器都对其进行了优化以指导初始化。 (GCC has an option to disable that optimization, though.)
(不过,GCC可以选择禁用该优化。)
By the way, you might want to take a look at http://en.wikipedia.org/wiki/Copy_constructor . 顺便说一句,您可能想看看http://en.wikipedia.org/wiki/Copy_constructor 。
In c++11 , rvalue references and move semantics can solve several types of unnecessary copies of temporaries, which occur in situations such as returning and passing arguments by value. 在c ++ 11中 ,右值引用和移动语义可以解决几种类型的不必要的临时副本,这些副本发生在诸如按值返回和传递参数的情况下。 So some of the don'ts you listed no longer apply in the new standard.
因此,您列出的某些内容不再适用于新标准。
IMO you're going backwards. IMO,你倒退了。 Especially taking into account that in optimized build majority of your cases will have all temporaries completely removed.
特别要考虑到,在优化的构建中,大多数情况下将完全删除所有临时工。
The suggested way is to write a correct program in a style that is easy to review. 建议的方法是以易于查看的方式编写正确的程序。 Then if you are not happy with performance, drop profiler at it, and fix the small portion that takes up most of time.
然后,如果您对性能不满意,请放下Profiler,然后修复占用大部分时间的一小部分。 Practice shows it is quite rarely where programmers think it will be.
实践表明,程序员很少会想到它。
The one thing to avoid from your list is params by value for class types with unpredicted size. 从列表中避免的一件事是具有不可预测大小的类类型的按值参数。 Most time const& is okay.
大多数时间const&都可以。
Avoiding assigments and sticking to initialization is a good guideline too, but not for performance reasons. 避免分配和坚持初始化也是一个很好的指导原则,但出于性能考虑并非如此。 Certainly it often does not apply for some types like collections.
当然,它通常不适用于某些类型,例如集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.