Search code examples
c++boost

Deciding to use at runtime a boost::static_vector or a std::vector


I have an application that I want to minimize dynamic allocation for efficiency.

I'm leaning forward using boost::static_vector in one of my classes for that reason. I'm not sure yet exactly how big my array will need to be to accommodate most situations but there are always exceptions...

Instead of discarding the input that would require more space than what my static_vector can store, I would like to fall back on std::vector to handle those exceptions.

A pattern that I commonly use in my classes design, is that I provide its input to the constructor to populate its container, then I provide a getter function that returns a const reference to the inner container.

The possibility that the class might use one or another container is causing a mental blind spot in me.

What would be the best way to offer access to the class elements?

I have come up with few ideas but none are truly satisfactory...

  1. Make my class a container using the proxy/facade pattern I'm too lazy for doing that and this is not practical if I want to apply this static_vector/vector solution everywhere...

  2. Place the burden on the class user ie.

void foo(HybridContainerObj &ojb) {
    if (obj.IsUsingStaticVector()) {
        const boost::static_vector<SomeElem> &vRef = obj.getStaticVec();
    }
    else {
        const std::vector<SomeElem> &vRef = obj.getVec();
    }
}

I doesn't feel right to me...

  1. Modify boost::static_vector to do exactly what I have in mind

So far, this is my favorite solution...

  1. Use some C++ magic that I am unaware of

Since both container classes do implement the same STL container concept, I wish that something along the lines would be possible:

const auto &vecRef = obj.getVec();

but AFAIK, this isn't possible... right?

So, I'm here to see what others think of that problem and if someone would have an elegant proposal to present the class used container elements to its users...

Greetings


Solution

  • boost::small_vector may be the combination you are looking for. From https://www.boost.org/doc/libs/1_60_0/doc/html/boost/container/small_vector.html:

    small_vector is a vector-like container optimized for the case when it contains few elements. It contains some preallocated elements in-place, which can avoid the use of dynamic storage allocation when the actual number of elements is below that preallocated threshold.