devxlogo

Optimize With the Named Return Value

The named return value is an automatic optimization that a compiler applies in order to eliminate the construction and destruction of a temporary object. When a temporary object is copied to another object using a copy constructor, and none of these objects is const or volatile, the Standard allows the implementation to treat the two objects as one, and not perform a copy at all.

   class A {  public:    A();    ~A();    A(const A&);    A operator=(const A&);  };  A f()  //return A by value  {    A a1;    return a;  }  A a2 = f();

The object a1 does not need to be copied when f() returns. Instead, the return value of f() can be constructed directly into the object a2, thereby avoiding both the construction and destruction of a temporary object on the stack.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.