Custom STL Allocator with a custom constructor

人走茶凉 提交于 2019-12-23 03:33:15

问题


I'm using the STL allocator mentioned here.
The only change I'm making is that I'm inheriting from a base class called Object, and I use base class' new and delete functions for allocation.

    class MyAlloc :public Object{
    ......
    }

I want to use the parameterized constructor of the base class which will be based on parameter sent to the STLAllocator, which would be something like this.

    MyAlloc(A *a) : Object(a) {
    ... }

And then use this constructor like :

   A *a = new A();
   std::vector<int,MyAlloc<int> (a) > v;

I'm not able to achieve this. It is resulting in compilation error :
'a'cannot appear in a constant-expression
template argument 2 is invalid
Thanks in advance..:)


回答1:


You specify the type of the allocator as a template argument and, if you don't want a default-constructed one, a value as a constructor argument:

std::vector<int,MyAlloc<int>> v((MyAlloc<int>(a)));

Note that I added an extra pair of parentheses to avoid the "most vexing parse". In this case, we can't avoid that using brace-initialisation, since that will try to use the initialiser list to populate the vector.



来源:https://stackoverflow.com/questions/18575746/custom-stl-allocator-with-a-custom-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!