Domanda

In C++ 11, we're encouraged to use auto for variable type,
does this also apply when initializing type like class and vector?

I mean should we write the following:

auto a = 10; 
auto b = MyClass();
auto c = vector<int>{1, 2, 3}; 

instead of:

auto a = 10;
MyClass b;
vector<int> c = {1, 2, 3}; 
È stato utile?

Soluzione

auto is just a handy shortcut to simplify things like

VeryLongClassName *object = new VeryLongClassName();

Now it will be

auto *object = new VeryLongClassName();

There is no reason to write

auto a = 10; 
auto b = MyClass();
auto c = vector<int>();

because it is longer and harder to read than

int a = 10;
MyClass b;
vector<int> c; 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top