Question

I need to constantly allocate a shared array of unsigned char as raw buffer to hold data from a TCP stream then pass it to several other threads for processing. My question is, does boost::make_shared<T[]>(std::size_t) value initialize or default initialize the underlying array? The former has too much overhead because of the high frequency (about ten times per second). I tried looking at the source code, but there are too many helper classes to get a clear understanding of what it does under the hood.

Was it helpful?

Solution 2

From the docs:

Effects: Allocates memory suitable for an array of type T and size size and constructs an array of objects in it via the placement new expression new(pointer) T() or new(pointer) T(args...). allocate_shared uses a copy of allocator to allocate memory. If an exception is thrown, has no effect.

This is performing value initialization of the array, as it value initializes each of the elements one at a time.

Boost also provides a make_shared_noinit version of the make_shared function for arrays, which perform no initializations of the array. That might better suit your needs.

OTHER TIPS

From Boost: make_shared and allocate_shared for arrays:

template<typename U> // U = T[]
shared_ptr<U> make_shared_noinit(size_t size);

template<typename U, typename A> // U = T[]
shared_ptr<U> allocate_shared_noinit(const A& allocator, size_t size);

Description: These overloads do not perform any value initialization of elements.

template<typename U> // U = T[N]
shared_ptr<U> make_shared_noinit();

template<typename U, typename A> // U = T[N]
shared_ptr<U> allocate_shared_noinit(const A& allocator);

Description: These overloads of the utilities above are for a fixed size array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top