What is the difference between declaring a variable using auto and using a type name?

For example, I have a class DataPacket. What's the difference between:

auto packet = DataPacket(); 

and

DataPacket packet;

?

+5
source share
5 answers

To answer the question about auto, firstly, there is no difference in the generated code between:

auto packet = DataPacket(); 

and

DataPacket packet = DataPacket();

But that is not what you wrote.

- , - packet . , , , packet ( , copy/move .) - packet, , , , , :

struct DataPacket { int i; };
{
  DataPacket packet = DataPacket();
  ++packet.i;  // OK
}
{
  DataPacket packet;
  ++packet.i;  // undefined behaviour
}

Xeo , :

auto packet = DataPacket();

DataPacket packet{};

, , , .

, copy/move, ( ) elided, - /. , .

+14

- , , .

+10

, , , . ( ).

: , , . .

+4

auto , . , , . auto .

auto, , ( ). . : .

, auto RTTI. .

C auto , "" , .

+1

( auto), .

, :

map<int, pair<string, double>> M;
.... // Fill up M
// Without "auto":
map<int, pair<string, double> >::iterator it = M.find(5);
// With "auto":
auto autoit = M.find(5);
// Yet another example:
// Without auto:
for (pair<const int, pair<string, double>>& x: M) {
   // Do stuff
}
// With auto:
for (auto& x : M) {
   // Do stuff
}
0

All Articles