Construction From vector<char> ?

Marc Glisse marc.glisse at normalesup.org
Thu Aug 14 14:33:21 CEST 2008


On Wed, 13 Aug 2008, David Gillies wrote:

> mpz_import() will indeed do the trick if you have a big chunk of
> bytes, and it can even get round endianness issues. The problem you
> have is that C++ makes no pledges about the in-memory representation
> of container types.

Well, it actually does, precisely for vector.

> A vector<char> may well use a member of type char*
> to store a flat array of its contents, but nothing says it has to, and
> nothing says you can get at it anyway without doing something evil.

23.2.4.1 of C++03 says:

The elements of a vector are stored contiguously, meaning that if v is a 
vector<T, Allocator> where T is some type other than bool, then it obeys 
the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

This sentence was absent in C++98.

> Further, even if you have access to the raw data as a pointer to an
> array, you can't just simply reinterpret_cast the pointer to be
> mp_limb_t* (at least not portably - there's no ironclad law that says
> a long is four bytes in a row, for example, and you'll probably bus
> fault on unaligned data on a lot of machines).

IMO endianness is a larger issue here.

> So mpz_import() will be stuck doing a bytewise import.

On a system where it is appropriate (in particular with the right 
endianness), there is no reason mpz_import can't do a single large memcpy 
(I haven't looked at the implementation so I don't know if it does).

-- 
Marc Glisse


More information about the gmp-discuss mailing list