With the introduction of C 11, developers gained a new set of syntax options for initializing classes, adding to the already existing brace-enclosed initializer. This plethora of choices has presented a puzzling dilemma: when to use each syntax option?
The provided guideline suggests that if the intent is to assign an exact value to an object, copy initialization (=) should be favored. This is because it minimizes the risk of inadvertently invoking an explicit constructor with potentially different semantics. Brace initialization should be considered if copy initialization is unavailable, and parentheses initialization should be used as a last resort.
Curly braces initialization excels when initializing with multiple values intended to be stored within the object. This syntax is particularly suitable for vectors, arrays, and complex numbers.
When the values provided during initialization describe the intended state or behavior of the object rather than its actual data, parentheses initialization should be employed. This is often the case with arguments specifying size or file names.
Consider the following code snippets:
{ // Example 1
int b(1); // Copy initialization for exact value
int a{1}; // Brace initialization for stored value
int c = 1; // Parentheses initialization for descriptor value (e.g., size)
int d = {1}; // Brace initialization for stored value
}
{ // Example 4
std::function a(std::plus()); // Copy initialization for callback function
std::function b{std::plus()}; // Brace initialization for callback function, likely unwanted
}
By following the proposed guideline, developers can navigate the complexities of C 11 initializer syntax with confidence, ensuring their code is both accurate and efficient.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3