从共享指针的解引用值获取共享指针 [英] Get a shared pointer from a dereferenced value of a shared pointer

查看:446
本文介绍了从共享指针的解引用值获取共享指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,有一个共享指针向量

Imagine having a vector of shared pointers

typedef vector< shared_ptr< classA > > PointerVector;

还有一个B类,该B类还具有一个共享指针向量,并且该方法将已经取消引用的共享指针推回到该向量中.

And a Class B which has as a member a vector of shared pointers as well, and a method that pushes back in this vector an already dereferenced shared Pointer.

ClassB
{
public:
    void add(classA &ref);
private:
    PointerVector vector;
}

假设main向add函数提供了已取消引用的shared_ptr< classA>实例:

Assume that main feeds the add function with a dereferenced shared_ptr< classA > instance:

主要:

shared_ptr< classA > sharedptr ( new classA );
ClassA &ref = *sharedptr;
ClassB B;
B.add(ref);

是否有一种方法可以实现add函数来接受已取消引用的共享指针并将其转换为初始共享指针?然后将其推回矩阵中?

Is there a way to implement the add function to accept a dereferenced shared pointer and convert it to the initial shared pointer? and then push it back in the matrix?

这就是我想要做的:

void ClassB::add(classA &ref) {
    shared_ptr< classA > ptr = &ref;
    vector.push_back( ptr );
}

注意1::将classA添加到向量中时,我希望共享指针计数增加一.我不需要创建另一个共享指针,而是想找到"对象先前拥有的共享指针.

NOTE1: When the classA is added to the vector, i want the shared pointer count increased by one. I dont need to create another shared pointer, i want to "find" the shared pointer the object previously had.

注意2:,因为我目前在tr1中,所以我无法使用make_shared

NOTE2: i cannot use make_shared because i am currently in tr1

推荐答案

通常,您不能仅"find" 指向对象的指针,因为无法跟踪是否指向特定对象.您应该自己设计这种机制,或者使用标准库提供的一种机制: enable_shared_from_this .

Generally you cannot just "find" pointers to object, as there is nothing keeping track if particular object is pointed to or not. You should either devise such mechanism yourself or use one provided by standard library: enable_shared_from_this.

步骤1:从std::enable_shared_from_this派生您的类,并提供一个成员函数来获取指针:

Step 1: derive your class from std::enable_shared_from_this and provide a member function to get pointer:

#include <memory>

struct ClassA: std::enable_shared_from_this<ClassA>
{
    std::shared_ptr<ClassA> get_pointer() 
    {
        return shared_from_this();
    }
    //...
};

第2步:确保要获取其指针的所有对象均由shared_ptr管理:

Step 2: Make sure all objects you want to get pointers for are managed by shared_ptr:

std::shared_ptr<ClassA> original_ptr(new ClassA);

第3步:只要要获取对象的共享指针,就调用第1步中定义的函数:

Step 3: call function defined in step 1 whenever you want to get a shared pointer to object:

void ClassB::add(classA& ref) {
    shared_ptr<classA> ptr = ref.get_pointer();
    vector.push_back( ptr );
}

这篇关于从共享指针的解引用值获取共享指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆