My goal here is to implement a simple version of unique_ptr which offers only a constructor, destructor, ->, *, and release().
However, I don't know what to do in the case where a unique_ptr is initialized using a non-allocated pointer.
eg
int i = 0; unique_ptr<int> p{&i}; If the unique_ptr simply calls delete on it owned pointer, this will produced undefined (and undesirable) behavior, at least as far as I know. What can I do to prevent this?
EDIT: My attempt at the problem is as follows...
template<typename T> class Uptr { public: Uptr<T>(T* pt) : mp_owned{pt} {} ~Uptr<T>() {delete mp_owned;} Uptr<T>(const Uptr<T>&) = delete; Uptr<T>& operator=(const Uptr<T>&) = delete; T& operator*() const {return *mp_owned;} T* operator->() const {return mp_owned;} T* release() {return mp_owned;} private: T* mp_owned; };
unique_ptr. But to answer your specific question - you can't do anything, reliably/portably (at least not last time I was familiar with C++).unique_ptris that it is the sole owner of the resource. If thestackowns it, then aunique_ptrshouldn't point to it.