Boost logo

Boost :

Subject: Re: [boost] [Interprocess] Named pipe interface proposal
From: Jason Roehm (jasonr_at_[hidden])
Date: 2013-08-11 21:25:21

On 08/11/2013 08:56 PM, Marshall Clow wrote:
>> Accessing an element of an empty vector is undefined behavior. Calling resize() to reserve space also causes elements to be initialized, which is often not needed when calling an API that indicates the number of bytes written.
>> What I often do is the following:
>> std::vector<char> v;
>> v.reserve(1024);
>> v.push_back(0);
>> read(&v[0], v.capacity());
>> That can be simplified by a wrapper class.
> Rob --
> Could you have meant "resize()" instead of "reserve()" here?

I think he meant reserve() here, for the reason indicated above the code
example. Using std::vector::resize() causes any newly-added elements to
be initialized, which may be a waste of effort if you're just passing
that vector to a function whose job is to fill it with new data. Using
reserve() instead will allocate the required memory but won't initialize
it. I agree that the intent of the above code perhaps isn't readily
apparent (and if you're going to use it that way, it would make sense to
wrap the code to hide that implementation detail), but I can see the
argument for using it. I've had some applications in the past where
large (multi-GB) buffers were being allocated using std::vector
instances, and in some cases, the time it took to default-initialize all
of the elements was non-trivial (or even a bottleneck!)


Boost list run by bdawes at, gregod at, cpdaniel at, john at