问题
I get this:
warning C4244: 'initializing' : conversion from 'uintmax_t' to 'unsigned int', possible loss of data
on:
boost::shared_array<char> buffer( new char[file->size]);
…and then this:
warning C4244: 'argument' : conversion from 'uintmax_t' to 'size_t', possible loss of data
on:
boost::asio::write(*socket, boost::asio::buffer(buffer.get(), file->size));
Shall I be scared or it is ok?
回答1:
Probably file->size
is of type uintmax_t
which is larger than the size_t
that operator new[]
takes for the array size. Typically the first one could be a 64bit integer while the second one would only be a 32bit.
Practically this will lead to problems when you are trying to handle files over 4GB, because the size_t
can't represent such a large number of bytes. If you only expect to handle smaller files where size_t
is large enough to store the file size, there won't be a problem.
回答2:
It depends on the implementation.
uintmax_t
is the largest unsigned type provided by the implementation. size_t
is the type of the result of the sizeof
operator, big enough to hold the size of any object. unsigned int
is, of course, the unsigned version of the type int
.
The only guarantees are that size_t
and unsigned int
are both at least 16 bits (but likely to be bigger), uintmax_t
is at least 64 bits (assuming C99 rules), and uintmax_t
is at least as wide as any other unsigned type.
Presumably file->size
is the size in bytes of a file, and it's probably of type uintmax_t
. Depending on the system, the maximum size of a file may well be bigger than the size of any possible object in memory.
If the size of this particular file isn't too big, there's no problem. But if size_t
is 32 bits (implying objects can't be bigger than 4 gigabytes), and your file is, say, 5 gigabytes, then you won't be able to allocate an in-memory buffer big enough to hold the contents of the file.
And the maximum value of size_t
, SIZE_MAX
, is only an upper bound on the maximum size of an object. Just because SIZE_MAX
is 2**31-1, that doesn't necessarily mean you can actually create an object that big.
回答3:
It depends on how big your files are.
Most computers have larger disk storage than RAM, and in many cases can support a single file too large to fit into RAM. In such a case, the allocation may fail, or the file size may be truncated to the size of a pointer, in which case you'll allocate a buffer which is not large enough to hold the file.
You can detect files of excessive size with:
size_t buffersize(file->size);
if (buffersize != file->size) { /* error, file too large to fit into virtual memory */ }
/* use buffersize for buffer allocation */
This would also make the warnings go away.
来源:https://stackoverflow.com/questions/7706171/what-is-the-loss-of-data-in-uintmax-t-to-size-t-and-unsigned-int-conversio