C++ static_cast

型別轉換:C v.s. C++

C語言裡的型別轉換在C++中被分成了 static_castdynamic_castconst_castreinterpret_cast等四種不同的方式,這是為了確保在不同的情況下,型別轉換的代碼都能work as expected。

static_cast

根據static_cast conversion

implicit conversion sequence from expression to new_type

static_cast可用於implicit conversion,而根據Implicit conversions,numeric promotion屬於implicit conversion。所謂的numeric promotion,指的是:

prvalues of small integral types (such as char) may be converted to 
prvalues of larger integral types (such as int).

也就是將佔用byte數較少的型別轉換為佔用byte數較多的型別。

TensorRT/blob/master/samples/common/buffers.hBufferManager的建構子中,使用static_castint型別的變數轉為size_t型別:

int mBatchSize;
static_cast<size_t>(mBatchSize);

我們知道int型別佔用4 bytes。那麼size_t呢?摘自About size_t and ptrdiff_tsize_t型別在不同作業系統上的大小為:

On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.

在32-bit系統上佔4 bytes,在64-bit系統上佔8 bytes。

所以將int轉為size_t屬於numeric promotion,因此也是implicit conversion,所以是在static_cast的適用範圍內。

參考連結

static_cast conversion

Implicit conversions

About size_t and ptrdiff_t

Why use static_cast(x) instead of (int)x?

static_cast in C++ | Type Casting operators

C++四种类型转换运算符:static_cast、dynamic_cast、const_cast和reinterpret_cast

发布了99 篇原创文章 · 获赞 9 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/keineahnung2345/article/details/104088562
今日推荐