文章预览
在上一篇文章 性能大杀器:std::move 和 std::forward 中,我们简单的介绍了下移动语义,今天聊聊编译器的一个常见优化 拷贝消除(copy elision) 。 move和copy elision是一种常见的编译器优化技术,旨在避免不必要的临时对象的复制和拷贝,对于那种占用资源比较多的对象来说,这种优化无疑会很大程度上提升性能。 且看一个例子,如下: #include struct Obj { Obj () { std::cout < "Default ctor" < } Obj ( const Obj & r) { std::cout < "Copy ctor" < } int x_ = 0 ; }; Obj CreateObj1() { return Obj (); } Obj CreateObj2() { Obj temp; temp.x_ = 42 ; return temp; } int main() { Obj o1(CreateObj1()); Obj o2(CreateObj2()); return 0 ; } 编译并运行上述代码,输出: Default ctor Default cto
………………………………