简体   繁体   中英

C4267: 'return' : conversion from 'size_t' to 'const UINT', possible loss of data

How to resolve below warning using typecast to const UINT?

C4267: 'return' : conversion from 'size_t' to 'const UINT', possible loss of data

Class CManager
{
   std::vector<CString>    m_ncount;
   public:
    const UINT GetMCount( int nInst) const;
}


const UINT CManager::GetMCount( int nInst) const
{
     return m_ncount.size();//C4267
}

Is this correct?:

const UINT CManager::GetMCount( int nInst) const
{
     return (const UINT)m_ncount.size();//C4267
}

UINT (which is not standard. unsigned int is the standard one actually) is at least 16 bit which means it is implementation dependable. No guarantees that it would work as an index or container size . However, size_t size is, by definition, exactly as output of sizeof operator. Which is guaranteed to work in all cases on all platforms.

So, the solution is to use size_t . Any other solution will be working around with ignoring the actual problem. Be thankful for your compiler warning!

If you might need to hold more than INT_MAX items in your vector, use size_t . In most cases, it doesn't really matter, but I use size_t just to remove the warning.

Just try this one

std::size_t CManager::GetMCount( int nInst) const
{
     return m_ncount.size();
}

If you are using UINT then you are coding probably under windows. In 32bit applications sizeof(UINT) and sizeof(size_t) are equal to 4, but under 64bit builds this is not true, sizeof(UINT) is 4 but sizeof(size_t) is 8.

One solution is to use UINT_PTR , also whatever type you will stay with add static assertion, ex:

static_assert(sizeof(UINT_PTR) == sizeof(size_t), "size_t must equal to ULONG_PTR");

If you are not bound to windows platform and its specific type macro definitions, then consider returning size_t .

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