Question: How can I return a non-const ref from a static class function, and why is the code below not doing so?
I am trying to initialize vectors with a custom allocator that itself is initialized with a reference to a custom memory management class. Here's what that looks like:
Custom std::vector allocator initialized with reference to custom memory management class
template <class T, std::size_t N, std::size_t MAX_SIZE, int ID>
class short_alloc
{
arena<N, MAX_SIZE, ID>& a_; //this is the custom memory mgmt class
...
public:
short_alloc(arena<N, MAX_SIZE, ID>& a) noexcept : a_(a) {
std::cout<< "copying from reference" << std::endl;
}
However, I wish to have only 1 memory manager per template type, so I am trying to initialize the allocator with a singleton's GetInstance()
method so that only 1 memory manager is created per template type:
Singleton class to ensure only 1 memory manager for each set of template parameters
template <typename T>
class Singleton
{
public:
static T* m_instance;
static T& GetInstance(){
if(!m_instance){
m_instance = new T();
}
return m_instance;
};
};
Use case:
I instantiate vectors with the custom allocator/memory manager class like so:
template <class T, std::size_t N, std::size_t MAX_SIZE, int ID>
class SmallVector {
public:
std::vector<T, short_alloc<T, N, MAX_SIZE, 1>> vec;
SmallVector() : vec(Singleton<arena<N, MAX_SIZE, ID>>::GetInstance()){
std::cout << "running constructor" << std::endl;
}
...
}
and invoked in int main()
like so:
SmallVector<int, MAX_BLOCK, MAX_INDIV, 1> s;
However, this yields a compiler error:
error: invalid initialization of non-const reference of type 'arena<3200ul, 400ul, 1>& from an rvalue of type 'arena<3200ul, 400ul, 1>*' return &m_instance;
So it seems as though my Singleton class is returning a const reference/r-type reference. How can I instead return an l-type reference?