Ray's playground

 

Item 20: Facilitate the return value optimization.(More Effective C++)

The rules for C++ allow compilers to optimize temporary objects out of existence. As a result, if you call operator* in a context like this,

    Rational a = 10; 
    Rational b(1, 2); 
    Rational c = a * b;                          // operator* is called here 

your compilers are allowed to eliminate both the temporary inside operator* and the temporary returned by operator*. They can construct the object defined by the return expression inside the memory allotted for the object c. If your compilers do this, the total cost of temporary objects as a result of your calling operator* is zero: no temporaries are created. Instead, you pay for only one constructor call — the one to create c. Furthermore, you can't do any better than this, because c is a named object, and named objects can't be eliminated

posted on 2012-03-09 14:08  Ray Z  阅读(191)  评论(0编辑  收藏  举报

导航