c++ - 为什么这个 auto_ptr 的 dynamic_cast 会失败?

标签 c++ casting

    #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 就无法获得所有权。目前还不清楚该对我做什么。你可能不得不说,如果类型转换失败,a 将继续拥有所有权——这听起来会造成严重的麻烦。最好开始使用 shared_ptr。两者 ab然后会指向同一个对象——但是B作为shared_ptr<B>a作为shared_ptr<A>

关于c++ - 为什么这个 auto_ptr 的 dynamic_cast 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/518959/

相关文章:

c++ - ELI5 : What is the data type of `int *p[]`

c++ - 问题向下转换到子类,多态性不起作用

casting - 在 Swift 中将字节转换为字符

c - 将 float 指针类型转换为 char 指针时会发生什么?

C++非完全构造的对象释放

c++ - 将大型单 block 单线程应用程序转换为多线程体系结构的建议?

尽管使用指针将其初始化为一维,但 C++ 仍将数组用作多维

c++ - 为什么我的多线程程序没有正确终止?

c++ - 直接初始化 unsigned short 的标准行为

c - 是否可以分配具有强制转换前缀的变量? (在宏内)