考虑以下代码:

class Base{

};

class Derived : public Base{

};

int main(int argc, char **argv)
{
        std::unique_ptr<Base> b(new Derived());//1 // b is Base object but holds Derived pointer
        Base *b1 = new Derived();//Base obj points to Derived //3
        //std::unique_ptr<Base*> b(new Derived());//2
        return 0;
}

在第二个语句(// 2)中,我遇到编译错误,但是如果考虑语法(// 3),为什么会出现此错误,应该提供指针类型而不是类类型的unique_ptr。

我是C++中智能指针的新手。

提前致谢。

最佳答案

std::unique_ptr<T>T的智能指针;也就是说,它类似于T*,但更智能。

因此,std::unique_ptr<Base*>Base*的智能指针;也就是说,它类似于Base**,但更智能。

关于c++ - C++智能指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29026390/

10-11 23:20
查看更多