gpt4 book ai didi

C++智能指针

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:52 25 4
gpt4 key购买 nike

考虑以下代码:

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++智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com