繁体   English   中英

来自const指针的共享指针

[英]Shared pointer from const pointer

假设我有一个返回的函数

const MyType*

我可以将结果捕获到shared_ptr吗? 怎么样?

您可以使用默认构造函数来执行此操作。 顺便说一句, 有一个陷阱 :提防const T - T指针共享!

#include <iostream>
#include <memory>
using namespace std;

class MyType {
    public:
};

const MyType* fun() {
    return new MyType();
}

int main() {

    {
        shared_ptr<const MyType> new_ptr(fun());

        // Use your pointer..

        shared_ptr<MyType> other_ptr(new MyType());
        shared_ptr<const MyType> other_ptr2 = other_ptr; // T to const T, allowed

        shared_ptr<MyType> new_ptr2 = new_ptr; // const T to T - NOT ALLOWED
    }

    return 0;
}

http://ideone.com/OOPdLu

一个shared_ptr<MyType const>可以解决这个问题,但是在走那条路线之前,我会非常确定自己可以做到; 例如,如果返回的值没有分配给new ,或者已经在shared_ptr

shared_ptr可以接受const类型作为其类型。

std::shared_ptr<const MyType>

因此,您可以像这样使用它:

std::shared_ptr<const MyType> pResult(SomeFunction());

但是,这假定从函数返回的值是函数内部的new ,并且函数调用者对返回的指针负责。

暂无
暂无

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

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