简体   繁体   English

C ++智能指针

[英]C++ smart pointer

consider the following code: 考虑以下代码:

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;
}

In the second statement(//2), I am getting compilation error, but if we consider syntax(//3), why I am getting this error, unique_ptr should be supplied pointer type instead of class type. 在第二个语句(// 2)中,我遇到编译错误,但是如果考虑语法(// 3),为什么会出现此错误,应该提供指针类型而不是类类型的unique_ptr。

I am new to smart pointers in c++. 我是C ++中智能指针的新手。

Thanks in Advance. 提前致谢。

std::unique_ptr<T> is a smart pointer to T ; std::unique_ptr<T>指向T的智能指针 that is, it resembles T* but smarter. 也就是说,它类似于T*但更智能。

Therefore, std::unique_ptr<Base*> is a smart pointer to Base* ; 因此, std::unique_ptr<Base*>指向Base*的智能指针 that is, it resembles Base** but smarter. 也就是说,它类似于Base**但更智能。

std::unique_ptr (and other pointers) take the type of the object it should point to, not of the pointer. std::unique_ptr (和其他指针)采用其应指向的对象的类型,而不是指针的类型。

Think of it like this: 这样想:

  • Regular pointer: T becomes T* 常规指针: T变为T*
  • Unique pointer: T becomes unique_ptr<T> 唯一指针: T变为unique_ptr<T>

The class template unique_ptr<T> manages a pointer to an object of type T. 类模板unique_ptr<T>管理指向类型T的对象的指针。

This is how unique_ptr is defined: 这是unique_ptr的定义方式:

template<
    class T,
    class Deleter = std::default_delete<T>
> class unique_ptr;

It should be given the type T. 它应该被赋予类型T。

So if you need a pointer to Base , you should give it type Base . 因此,如果您需要一个指向Base的指针,则应为其指定Base类型。 If you give it Base* , it will become pointer to pointer to Base . 如果给它Base* ,它将成为指向Base指针。

See more details here: http://en.cppreference.com/w/cpp/memory/unique_ptr or here http://www.cplusplus.com/reference/memory/unique_ptr/unique_ptr/ 在此处查看更多详细信息: http : //en.cppreference.com/w/cpp/memory/unique_ptr或此处http://www.cplusplus.com/reference/memory/unique_ptr/unique_ptr/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM