c – 为什么auto_ptr的dynamic_cast会失败?

c – 为什么auto_ptr的dynamic_cast会失败?,第1张

概述#include "iostream" class A { private: int a; public : A(): a(-1) {} int getA() { return a; } }; class A; class B : pub
#include "iostream"    class A {        private:        int a;        public :        A(): a(-1) {}        int getA() {            return a;        }    };    class A;    class B : public A {        private:        int b;        public:        B() : b(-1) {}        int getB() {            return b;        }    };    int main() {        std::auto_ptr<A> a = new A();        std::auto_ptr<B> b = dynamic_cast<std::auto_ptr<B> > (a);        return 0;    }

错误:不能dynamic_cast`(& a) – > std :: auto_ptr< _Tp> :: get()const

解决方法 那么,std :: auto_ptr< B>不是从std :: auto_ptr< A>派生的.但是B来自A. auto_ptr不知道那个(它不是那么聪明).看起来您想使用共享所有权指针. boost :: shared_ptr是理想的,它还提供了dynamic_pointer_cast:
boost::shared_ptr<A> a = new A();boost::shared_ptr<B> b = dynamic_pointer_cast<B> (a);

对于auto_ptr,这样的事情无法真正起作用.因为所有权将转移到b.但如果演员表失败,b就无法获得所有权.目前还不清楚该怎么办.您可能不得不说,如果演员表失败,将继续拥有所有权 – 这听起来会导致严重的麻烦.最好开始使用shared_ptr.然后a和b都指向相同的对象 – 但是B作为shared_ptr< B>和a作为shared_ptr< A>

总结

以上是内存溢出为你收集整理的c – 为什么auto_ptr的dynamic_cast会失败?全部内容,希望文章能够帮你解决c – 为什么auto_ptr的dynamic_cast会失败?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1237917.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存