I am designing a wrapper class (a bit similar to std::autoPtr but I have different purpose) for scalar values:
template <typename T>
class ScalarPtr
{
private:
T* m_data;
...
public:
ScalarPtr(T *data): m_data(data)
{ ... }
T& operator* ();
T* operator -> ();
~ScalarPtr()
{
if(m_data)
delete m_data; ...
}
};
Now the problem is that when I also want to use this class for stack-allocated memory objects like this:
float temp=...
ScalarPtr<float> fltPtr(&temp);
The naive way is to pass boolean in constructor to specify whether to deallocate or not but is there any better way?
I am not sure if there is a better approach other than the boolean flag.
As you are aware(and hence ask the Q)this makes the interface rather non-intutive to the end user.
The purpose of the wrapper/resource managing class is to implement an RAII, where the resource itself takes care of releasing its resources(in this case dynamic memory) implicitly. Given that the stack variables are automatically destroyed beyond their scopes,its seems rather odd to use a resource managing wrapper for them. I would rather not prefer to do so.
But, Given that you want to maintain a uniform acess to your class through this wrapper class, the simplest yet not so elegant way seems to be the boolean flag.