简体   繁体   中英

What's the difference between type name() and type name = type()?

I'm new to C++ and trying to understand something. I have this code in my main.cpp:

Radio r = Radio("PSR", 100.8);

or that code:

Radio r("PSR", 100.8);

Both seem to work and doing the same thing. So what's the difference?

Radio r = Radio("PSR", 100.8); is copy initialization while Radio r("PSR", 100.8); is direct initialization .

C++17

From C++17 due to mandatory copy elison both are the equivalent.

Radio r = Radio("PSR", 100.8); //from C++17 this is same as writing Radio r("PSR", 100.8);

Prior C++17

But prior to C++17 , the first case Radio r = Radio("PSR", 100.8); may result in the creation of a temporary using which r is copy initialized. This is because prior to C++17, there was non-mandatory copy elison .


Another thing to note is that if you were to write:

type name(); //this is a function declaration

the above is a declaration for a function named name which has the return type of type and has 0 parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM