templated typedef?

前端 未结 4 1496
我寻月下人不归
我寻月下人不归 2020-12-04 19:10

I\'m using libgc, a garbage collector for C and C++. To make STL containers garbage collectible one must use the gc_allocator.

Instead of writing

s         


        
4条回答
  •  抹茶落季
    2020-12-04 20:12

    You can publicly inherit:

    template
    class gc_vector : public std::vector >
    {
        public:
        // You'll have to redeclare all std::vector's constructors here so that
        // they just pass arguments to corresponding constructors of std::vector
    };
    

    This solves your problem completely. The derived type can be used everywhere where the base type can be used, and there's no implementation overhead with any decent compiler.

    The fact that std::vector has non-virtual destructor might lead to undefined behaviour according to C++ standard if you ever try to delete a derived class variable through a pointer to base class variable.

    In real world this shouldn't matter in this particular case - the derived class has nothing new added compared to the base class and therefore the destructor for the derived class just calls the destructor for the base class. Proceed with paranoia, port carefully anyway.

    If you never allocate this class variables on heap (and it's typical to allocate vector variables on stack and as members of other classes) the non-virtual destructor problem doesn't affect you.

提交回复
热议问题