More Effective c++ 28. Smart Pointer

本文探讨了C++中auto_ptr智能指针的使用及其与继承的关系,特别是在私有继承下导致的编译错误,并提供了修改建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值