简体   繁体   中英

Custom STL Allocator with a custom constructor

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..:)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM