R_Kapp
R_Kapp

Reputation: 2858

Inheriting from STL containers

Reading StackOverflow Q&A's such as this and this, it would appear that inheriting from STL containers is generally a bad idea. I don't intend to do this in production code; however, I want to know if it will give me a valid quick and dirty test.

In our code, we make heavy use of the STL, and we wish to test how aligning memory to a 64-byte boundary will affect our code's performance. I was planning to test this by writing a simple custom allocator and having a simple class that inherits std::vector with the only change in the class being that the default allocator is my custom allocator and not std::allocator and then simply writing a script to use sed and replace all instances of std::vector with my new class. Using this approach, I will not ever have any pointers carrying through to the base class (all instances of std::vector have been replaced, so any pointers would be of my custom type instead), which appears to be the biggest concern with inheriting from STL. Is this a valid approach? Are there any other easier/safer alternatives? This is a 3 million line code base, so manually changing all instances of std::vector to use the custom allocator would be a very, very, time-consuming task to say the least.

Upvotes: 2

Views: 673

Answers (1)

Sam Cristall
Sam Cristall

Reputation: 4387

If you have C++11 support, rather than inheritance you could do a templated using statement:

template <class T>
using custom_vector = std::vector<T, custom_allocator<T>>;

Then use your script to sed std::vector to custom_vector.

Upvotes: 16

Related Questions