I'm implementing a smart pointer class, and having a couple of confusions. Would really appreciate if people could help me clarify.
1: I thought smart pointer class should have "new" in constructor, "delete" in desctructor. But I can't seem to find a place to put in "new"... So the user will be responsible to create new, while the smart pointer class helps to clean it up?
2: In designing copy assignment operator, a popular approach was to copy-n-swap in order to be thread-safe. However, copy-n-swap requires the object is passed in by value (not by reference). Can it still be used in designing a smart pointer? My concern was that this is a pointer class, hence may not be able to pass in by value. But I'm not very sure about this.
3: If I'm requested to code a smart pointer at interview, do I have to provide some type of reference count? Thought reference count is specific to the shared_ptr...
4: This must be a dumb question, but better ask then keep doubts inside. for SmartPointer<T>& sp
to access ptr, should it use sp->ptr
or sp.ptr
??
Appreciate your input.
template <class T>
class SmartPointer{
T* ptr;
public:
SmartPointer():ptr(NULL){}
SmartPointer(const T& p):ptr(p){}
SmartPointer(const SmartPointer<T>& sp):ptr(sp->ptr){}
SmartPointer<T>& operator=(const SmartPointer<T>& sp);
~SmartPointer(){delete ptr;}
T& operator*(){return *ptr;}
T* operator->(){return ptr;}
};
SmartPointer& operator=(const SmartPointer& sp){
T* pOrig = ptr;
ptr = new T(sp.ptr);
delete pOrig;
return *this;
}
1: I would say the constructor is such place:
then you gain the same syntax as in typical smart pointer - you create it by calling
SmartPointer objPtr(new Obj());
. User can create his object however he wants and the smart pointer is responsible to clean it up after him (as it's the major issue smart pointers was designed to help with). Note, that in future you may want to add some kind ofstd::make_shared()
method to avoid copying your wrapper while constructing and improve performance.2: You have to think of the way your smart pointer will behave. Remember that when you try to copy a raw pointer you copy address only, not an object itself. So, if you decide to treat SmartPointer like a normal pointer equipped with garbage collector then you can freely implement copy-n-swap. On the other hand, you can delete operator=() like it is in
std::unique_ptr
or try to implement reference counting like instd::shared_ptr
.3: I'd say only if you are requested to do so explicitly. Normally by smart pointer one can understand some kind of wrapper that is able to control raw pointer's lifetime by itself. Although, I'm sure if they ask "please write a simple smart pointer's implementation" and you ask "do you want it to handle shared ownership as well?", you will gain a point :)
4:
sp.ptr
of course :)SmartPointer<T>& sp
is a reference so in order to access its member you have to use a dot.
operator.To use
sp->ptr
you would have to have hadSmartPointer<T>* sp
parameter.