Puzzle 9Counting Copies

 #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};
 }

Guess the Output

images/aside-icons/important.png

Try to guess what the output is before moving to the next page.

images/hline.png

The program displays the following output:

 copy

Discussion

It may seem like three copies are being made in this program. ...

Get C++ Brain Teasers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.