For example, I have some class DataPacket. What is the difference between:
auto packet = DataPacket();
and
DataPacket packet;
?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To answer the question about
autofirst, there is no difference in the generated code between:and
But that’s not what you wrote.
In the original question, the first one creates a value-initialized temporary and then copy-initializes
packetfrom it. That requires an accessible, non-explicit copy or move constructor, requires the type can be default-constructed, and ensurespacketis initialized (assuming the copy/move constructor isn’t buggy.) The second one default-initializespacketwhich only requires that the type can be default-constructed, but leaves the object uninitialized if it has a trivial default constructor, for example:As Xeo points out in a comment below, these is less difference between these:
because the second of those also ensures value-initialization, so in that case the difference is that the former requires an accessible, non-explicit copy or move constructor.
In all the cases that require an accessible copy/move constructor, if the copy (or move) isn’t elided then the code generated will be different because of the copy/move. But in practice it will be elided by all modern compilers so the generated code will be identical.