series of articles
Regular expressions of C++11 (regex_match, regex_search, regex_replace)
C++11 thread library (Thread, Mutex, atomic, lock_guard, synchronization)
C++11 smart pointers (unique_ptr, shared_ptr, weak_ptr, auto_ptr) on memory management
Casting of C++11 (static_cast, const_cast, dynamic_cast, reinterpret_cast)
Lambda expression (anonymous function) of C++11
Rvalue references in C++11: move semantics and perfect forwarding
C++11 inheritance constructor (using declaration)
Delegating constructors in C++11
Explicit conversion operator in C++11-explicit
Article directory
Type narrows
Type narrowing: refers to the implicit type conversion when data changes and precision is lost.
An important feature of list initialization is that it prevents type narrowing ( narrowing
).
Scenarios that lead to type narrowing
- Implicit conversion from floating-point to integer . For example
int num = 3.14;
, when a floating-point number is given to a variable of type int小数截断
. - Convert from high precision floating point to low precision floating point data . For example,
double d = 3.14159566; float f = d;
assigning adouble
variable of a type to a variable of a type and a variable of a type to a variable of a type will result in type narrowing.float
long double
double
- Convert from an integer (an enumeration type that is not an enumeration class) to a float . If the integer value is too large, the floating point type cannot be stored, and the type is narrowed.
- Convert from an integer (an enumeration type that is not an enumeration class) to a low-length integer . This case type second, e.g.
long long
convert toint
.
code demo
In the following code, when initialization is performed by an assignment expression or an expression in parentheses, even if the type is narrowed, no error will be reported, only a warning⚠. However, if the type is narrowed in the way of initialization list, it will cause a compilation error.
#include <iostream>
using namespace std;
/*
* 数据变化、精度丢失 都是类型收窄
*/
int main()
{
const int x = 1024;
const int y = 10;
char a = x; // 类型收窄
char* b = new char(1024); // 类型收窄
char c = {
x }; // 类型收窄 报错
char d = {
y };
unsigned char e = {
-1 }; // 类型收窄 报错
float f{
7 };
int g{
2.0f }; // 类型收窄 报错
float* h = new float{
1e48 }; // 类型收窄 报错
float i = 1.21;
return 0;
}
Summarize
List initialization was introduced in C++11, and list initialization can effectively prevent type narrowing. Generally speaking, the change of data will cause program errors with high probability, which effectively prevents some hidden dangers, which is also the difference between list initialization and other initialization methods.