4

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 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@gx_: Good point; I only parsed it with my brain, which is a bit buggy today.
Thanks for the help.. solutions works fine with std::vector but is not working with std::map. I have used it in the same way : std::map<std::string, std::string, std::less<std::string>, MyAlloc<std::pair<const std::string,std::string> > > x ((MyAlloc<std::pair<const std::string, std::string>(a))); Results here : ideone.com/C8hY19
@codinonwheels: Your allocator needs to meet the allocator requirements described in C++11 17.6.3.5 (or C++98 20.1.5, if you're stuck in the past). pointer is one of several members and nested types that it needs to provide.
Actually, looks like my allocator satisfies the requirements. I know this because if I don't have the value as construct argument, it works fine. The error crops in once I have a value as construct argument. Also, I wanted to know the value passed is right or not..! Please bear me.. I'm learning allocators.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.