C++ 11 自动初始化

标签 c++ c++11 auto

在 C++ 11 中,我们鼓励对变量类型使用 auto,
这是否也适用于初始化类和 vector 等类型?

我的意思是我们应该写以下内容:

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

代替:

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

最佳答案

auto 只是一个方便的快捷方式来简化诸如

VeryLongClassName *object = new VeryLongClassName();

现在是

auto *object = new VeryLongClassName();

没有理由写

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

因为它比它更长更难读

int a = 10;
MyClass b;
vector<int> c; 

关于C++ 11 自动初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18556590/

相关文章:

c++ - 返回 C++ 中断循环的内部循环?

c++ - "unresolved external symbol"错误

c++11 - 将 char16_t 转换为 long/integer,(相当于 atoi/atol)

c++ - friend 模板特化声明中不允许使用 Consexpr?

c++ - 这是 "new auto(enum_type)"的 Microsoft VC++ 2010 编译器错误吗

c++ - "auto"变成了错误的类型?

c++ - 如何在 C++ (Linux) 中获得 CPU 时钟速度?

c++ - 如何将模板名称传递给方法?

c++11 - 去原子和内存顺序

c++ - 为什么在创建内置数组的模板函数中不允许使用 auto?