More Effective c++ 28. Smart Pointer

来源:互联网 发布:中远网络2017 编辑:程序博客网 时间:2024/06/15 09:11
template<class T>class auto_ptr {public:    explicit auto_ptr(T* p = 0);    template<class U>    auto_ptr(auto_ptr<U>& rhs);    ~auto_ptr();    template<class U>    auto_ptr<T>& operator=(auto_ptr<U>& rhs);    T& operator*() const;    T* operator->() const;    T* get() const;    T* release();    void reset(T *p = 0);private:    T *pointee;};template<class T>inline auto_ptr<T>::auto_ptr(T *p = 0) : pointee(p) {}template<class T>template<class U>inline auto_ptr<T>::auto_ptr(auto_ptr<U>& rhs) : pointee(rhs.release()) {}template<class T>inline auto_ptr<T>::~auto_ptr() {    delete pointee;}template<class T>template<class U>inline auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<U>& rhs) {    if (this != &rhs) reset(rhs.release());    //if (rhs.get() != this->get()) reset(rhs.release());    return *this;}template<class T>inline T& auto_ptr<T>::operator*() const {    return *pointee;}template<class T>inline T* auto_ptr<T>::operator->() const {    return pointee;}template<class T>inline T* auto_ptr<T>::get() const {    return pointee;}template<class T>inline T* auto_ptr<T>::release() {    T* oldPointee = pointee;    pointee = 0;    return oldPointee;}template<class T>inline void auto_ptr<T>::reset(T* p) {    if (pointee != p) {        delete pointee;        pointee = p;    }}

异常
C2243 ‘type cast’: conversion from ‘Drived ’ to ‘Base ’ exists, but is inaccessible
。。。。
E0269 conversion to inaccessible base class “Base” is not allowed

class Base{public:    void basemem() { };    int get() {         return i; }protected:    int i;};class Drived : private Base{ // 问题出在private 默认也是private 改为public就是    int use_base() { return i; }};int main() {    auto_ptr<Base> a(new Base);    auto_ptr<Drived> d(new Drived);    Drived* p = d.release();    p->basemem(); // 不可访问    Base* p1 = a.release();    p1->basemem(); // 可访问    p1 = p; // 该不该访问? 所以这样做编译器不允许 改成public inheritance 就好了    auto_ptr<Base> b(p1);}
原创粉丝点击