简体   繁体   中英

Warning C4267 'initializing': conversion from 'size_t' to 'DWORD', possible loss of data

I am getting the below warning message when compiling my C++ application,

Warning C4267 'initializing': conversion from 'size_t' to 'DWORD', possible loss of data at the below line:

DWORD nPos = strRegPath.find(REG_SOFTWARE); 

Below is my complete code:

Declaration:

#define REG_SOFTWARE L"Software"
wchar_t* m_wszParams;

Definition:

wstring strRegPath = m_wszParams;

DWORD nPos = strRegPath.find(REG_SOFTWARE); 

Could anyone please help me how to resolve this warning?

Thanks in advance.

The problem is caused by DWORD falling behind std::size_t in terms of size. If writing

std::size_t nPos = strRegPath.find(REG_SOFTWARE); 

merely kicks the can down the road, that is you get a warning elsewhere, then you can either force the issue with

static_cast<DWORD>(strRegPath.find(REG_SOFTWARE));

whereupon you're essentially telling the compiler you know what you're doing which ought to be sufficient to suppress the warning, or use something that makes a run-time check to verify you're not losing data: a numeric_cast from Boost can help there:

https://www.boost.org/doc/libs/1_38_0/libs/numeric/conversion/doc/html/boost_numericconversion/improved_numeric_cast__.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM