Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 11 initialization with auto

Tags:

c++

c++11

auto

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}; 
like image 461
user350954 Avatar asked Sep 01 '13 08:09

user350954


People also ask

Does C++11 have auto?

C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.

What do you mean by auto initialization?

Automatic initialization in Java Java does not initialize non-array local variables (also referred to as automatic variables) . The Java compiler generates error messages when it detects attempts to use uninitialized local variables. The Initializer program shows how automatic initialization works.

What is automatic initialization in C++?

You can initialize any auto variable except function parameters. If you do not explicitly initialize an automatic object, its value is indeterminate. If you provide an initial value, the expression representing the initial value can be any valid C or C++ expression.

Does C++ automatically initialize variables?

Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location!


1 Answers

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; 
like image 93
mas.morozov Avatar answered Oct 02 '22 22:10

mas.morozov