Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Beginner
Nov 4, 2008



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Avoiding Unnecessary Object Construction

One way to avoid unnecessary object construction is to use a reference instead of an object to store the unnamed temporary object returned by value.

This tip references both Scott Meyers' Effective C++ Item 23 ("Don't try to return a reference when you must return an object.") and Item 20 ("Facilitate the return value optimization.").

Here's the code:

const Rational& operator*(const Rational& lhs, const Rational& rhs)
    return Rational(lhs.n * rhs.n, lhs.d * rhs.d);

Rational a(1, 2);
Rational b(3, 5);
Rational c = a*b; // This incurs an additional object construction.

[const] Rational& c = a*b; 
// A better way of doing it. Here we just give the returned temporary object a name 'c'.
Budi Bong
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date