For educational purposes, I was earlier today implementing a wrapper class, defined below (this is taken from a book):
#ifndef WRAPPER_H
#define WRAPPER_H
template<class T>
class Wrapper
{
public:
Wrapper()
{ dataPtr = 0; }
Wrapper(const T& inner)
{
dataPtr = inner.clone();
}
Wrapper(const Wrapper<T> &original)
{
if (original.dataPtr != 0)
dataPtr = original.dataPtr->clone();
else
dataPtr = 0;
}
Wrapper &operator =(const Wrapper<T> &original)
{
if (this != &original)
{
if (dataPtr != 0)
delete dataPtr;
dataPtr = (original.dataPtr !=0) ? original.dataPtr->clone() : 0;
}
return *this;
}
~Wrapper()
{
if (dataPtr != 0)
delete dataPtr;
}
T &operator*()
{
return *dataPtr;
}
const T&operator*() const
{
return *dataPtr;
}
T *operator->()
{
return dataPtr;
}
const T * const operator->() const
{
return dataPtr;
}
private:
T *dataPtr;
};
#endif
The main idea is to act as a pointer, with the additional advantage of taking care of memory management, copy constructor, destructor and assignment operator. It wraps classes that have a clone method: they return a pointer to a copy of themselves (not to themselves, to a fresh copy made with new
Class(*this)
).
In some ways it seems to be like a unique_ptr
, because the object wrapped is only accessible through this wrapper. There is a difference, though, which is what my question is about. In this wrapper class, there is a constructor defined by accepting a reference to an object of the class it wraps (the first constructor in the code above).
This is very convenient. Let's say we have classes A
and B
, and the constructor for B
takes a reference to a Wrapper< A >
. Then I can construct an object B
with another object A
:
A object1;
B object2(A);
This is because object2
is used to construct a Wrapper< A >
(then passed to the constructor of B
) using the aforementioned Wrapper
constructor.
Is it possible to do this with any of the smart pointers in std::memory
? My main goal here is educational, but in practice I don't want to reinvent the wheel.