type
status
date
slug
summary
tags
category
icon
password
Why is Braced Initialization {} Generally Preferred?
As a general rule, initialization in C++ can be done with parenthesis, equal signs, or braces:
Braced initialization is also called uniform initialization. It is introduced in C++11 as a single initialization syntax that can be used anywhere and express everything. For example, before C++11, you couldn’t initialize a
std::vector
with a list of elements directly in its declaration. But after C++11, you can do this via braced initialization:.Braces can also be used to specify default initialization values for non-static data members:
Moreover, braces can be used to initialize uncopiable objects:
This is why braced initialization is called uniform - among C++’s three ways to designate an initializing expression, only braces can be used everywhere.
extra features for braced initialization
- it prohibits (禁止) implicit narrowing conversions among built-in types
- it’s immune to C++’s most vexing parse
takeaways
- braced initialization is the most widely usable initialization syntax, it prevents narrowing conversions, and it’s immune to C++’s most vexing parse
- during constructor overload resolution, braced initializers are matched to
std::initializer_list
parameters if at all possible, even if other constructors offer seemingly better matches.
- an example of where the choice between parentheses and braces can make a significant difference is creating a
std::vector<numeric type>
with two arguments
- choosing between parentheses and braces for object creation inside templates can be challenging, because the template author sometimes does not know which initialization method is correct
- general solution: choose one initialization method and document this decision as part of the interface.
- 作者:Zack Yang
- 链接:https://zackyang.blog/article/cpp-object-initialization
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章