Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will copy constructor be run for this code?

Given the following C++ code:

struct foo {
  // Some definition with copy constructor.
};

const foo &getData();

const foo &alt1(getData());
const foo &alt2 = getData();

Will a reasonable compiler produce different code for alt1 and alt2? In other words, will alt1 cause the copy constructor to be run, or is the compiler allowed to optimize that away and assign the reference directly?

like image 815
WilliamKF Avatar asked Feb 28 '26 17:02

WilliamKF


1 Answers

In both cases, you initialize a reference (not an object), so no copy-constructor will be run.

like image 97
zvrba Avatar answered Mar 03 '26 07:03

zvrba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!