在 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/