当前位置: 移动技术网 > IT编程>开发语言>JavaScript > More Effective c++ 28. Smart Pointer“编程开发”

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

2017年12月18日  | 移动技术网IT编程  | 我要评论

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); }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网