In C++, copy elision is an optimization technique that allows the compiler to eliminate unnecessary object copies, which can enhance performance. Named Return Value Optimization (NRVO) is a specific case of copy elision that occurs when the compiler optimizes the return of a local object from a function.
To leverage copy elision and NRVO, ensure that you return local objects directly rather than returning by value using pointers or references. This allows the compiler to construct the return value directly into the caller's space, thus avoiding the overhead of copying.
The following example demonstrates how to utilize NRVO in a simple C++ function:
#include
class MyObject {
public:
MyObject() { std::cout << "Constructed" << std::endl; }
MyObject(const MyObject&) { std::cout << "Copied" << std::endl; }
~MyObject() { std::cout << "Destructed" << std::endl; }
};
MyObject CreateMyObject() {
MyObject obj; // Local object
return obj; // NRVO allows elision, no copy
}
int main() {
MyObject obj = CreateMyObject(); // No copy occurs due to NRVO
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?