Search⌘ K
AI Features

Discussion: Counting Copies

Understand how C++ handles object copying with prvalues and return value optimization techniques like unnamed and named return value optimization (URVO and NRVO). Learn how modern compilers construct objects directly in caller memory, eliminating unnecessary copies to write more efficient and predictable C++ code.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
struct Resource
{
Resource() = default;
Resource(const Resource &other)
{
std::cout << "copy\n";
}
};
Resource getResource()
{
return Resource{};
}
int main()
{
Resource resource1 = getResource();
Resource resource2{resource1};
}

Understanding the output

It might seem like three copies are being made in this program. One to initialize the return object of getResource with the temporary Resource{}, one to initialize resource1 with said return object, and one to initialize resource2. However, no copies are being made when returning from getResource() and initializing resource1. How is this possible?

The pure rvalues (prvalues)

Let’s first look at the return statement, which seemingly initializes the return object from the temporary Resource{}. The Resource{} expression in the return statement is a type of rvalue called a prvalue, or the pure ...