Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code invoke the copy constructor?

I'm a C++ noob so I can't figure out why the line in Logger.cpp invokes the copy constructor...

Logger.h:

class Logger {
    public:
    Logger();
    ~Logger();
};

Logger LOGGER;

Logger.cpp:

Logger LOGGER = Logger(); // Copy constructor here
like image 269
Xenoprimate Avatar asked Apr 19 '26 10:04

Xenoprimate


1 Answers

The statement Logger() creates an anonymous temporary object.

LOGGER = Logger() copies that anonymous temporary into the object LOGGER. The copy constructor avoids having to construct LOGGER as something other than a copy of that temporary.

The compiler is allowed to optimize away this copy, but it's not required to. More here.

If you want to construct the object directly, just say Logger LOGGER;.

like image 117
Joe Z Avatar answered Apr 21 '26 03:04

Joe Z



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!