欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

More Effective c++ 28. Smart Pointer“编程开发”

程序员文章站 2022-06-24 20:22:08
More Effective c++ 28. Smart Pointer“编程开发” template class auto_ptr { publ...

More Effective c++ 28. Smart Pointer“编程开发”

template
class auto_ptr {
public:
    explicit auto_ptr(T* p = 0);
    template
    auto_ptr(auto_ptr& rhs);

    ~auto_ptr();
    template
    auto_ptr& operator=(auto_ptr& rhs);
    T& operator*() const;
    T* operator->() const;
    T* get() const;
    T* release();
    void reset(T *p = 0);
private:
    T *pointee;
};

template
inline auto_ptr::auto_ptr(T *p = 0) : pointee(p) {}

template
template
inline auto_ptr::auto_ptr(auto_ptr& rhs) : pointee(rhs.release()) {}

template
inline auto_ptr::~auto_ptr() {
    delete pointee;
}

template
template
inline auto_ptr& auto_ptr::operator=(auto_ptr& rhs) {
    if (this != &rhs) reset(rhs.release());
    //if (rhs.get() != this->get()) reset(rhs.release());
    return *this;
}

template
inline T& auto_ptr::operator*() const {
    return *pointee;
}

template
inline T* auto_ptr::operator->() const {
    return pointee;
}

template
inline T* auto_ptr::get() const {
    return pointee;
}

template
inline T* auto_ptr::release() {
    T* oldPointee = pointee;
    pointee = 0;
    return oldPointee;
}

template
inline void auto_ptr::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
a(new Base); auto_ptr d(new Drived); Drived* p = d.release(); p->basemem(); // 不可访问 Base* p1 = a.release(); p1->basemem(); // 可访问 p1 = p; // 该不该访问? 所以这样做编译器不允许 改成public inheritance 就好了 auto_ptr b(p1); }