![](/img/trans.png)
[英]std::streampos, std::streamoff and std::streamsize to long long int?
[英]Declaring an array with size std::streamoff
我有這行來獲取文件大小
std::streamoff _responseLength = _responseIn.tellg();
我正在為wchar_t指針分配內存,
wchar_t* _responseString = new wchar_t[_responseLength];
我收到有關'initializing' : conversion from 'std::streamoff' to 'unsigned int', possible loss of data
的警告'initializing' : conversion from 'std::streamoff' to 'unsigned int', possible loss of data
。
我應該怎么做才能完全消除編譯器的警告?
std :: streamoff是一個大的(至少64位)有符號整數(通常為long long
或int64_t
,如果為64位,則為long
)。 用於表示對象的大小以及數組和容器的長度的類型是size_t
,它是無符號的,通常是無unsigned long
。 您需要將流輸出值static_cast
到size_t。
請注意, tellg()
可能返回-1。 static_cast
-1 to size_t
將產生巨大的正值; 嘗試分配那么多的內存將導致您的程序失敗。 您需要在投放前明確檢查-1。
請不要使用裸指針和new
。 如果需要緩沖區,請使用以下命令:
std::vector<wchar_t> buffer(static_cast<size_t>(responseLength));
// use &buffer.front() if you need a pointer to the beginning of the buffer
用於分配內存的新運算符采用unsigned int
因此std::streamoff
被轉換為unsigned int
以符合要求。
這樣做的限制是,您不能讀取大於4GB的文件。
為避免此限制,您需要按適合內存的片段讀取文件。
如果您的文件只有大約100MB,請忽略該警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.