【发布时间】:2022-01-07 16:37:02
【问题描述】:
MyClass a1 {a}; // clearer and less error-prone than the other three
MyClass a2 = {a};
MyClass a3 = a;
MyClass a4(a);
为什么?
【问题讨论】:
-
没错,这很方便,但在我看来它降低了可读性——我喜欢在阅读代码时查看对象是什么类型。如果你 100% 确定对象是什么类型,为什么要使用 auto?如果你使用列表初始化(阅读我的答案),你可以确定它总是正确的。
-
@Oleksiy:
std::map<std::string, std::vector<std::string>>::const_iterator想和你谈谈。 -
@Oleksiy 我推荐阅读this GotW。
-
@doc 我会说
using MyContainer = std::map<std::string, std::vector<std::string>>;更好(尤其是因为你可以模板化!) -
天哪,只有在 C++ 中才存在这样的问题。非常感谢您提出这个问题,答案真的很有帮助
标签: c++ c++11 syntax initialization list-initialization