Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将派生智能指针指向基引用返回的堆栈对象_C++_Shared Ptr - Fatal编程技术网

C++ 将派生智能指针指向基引用返回的堆栈对象

C++ 将派生智能指针指向基引用返回的堆栈对象,c++,shared-ptr,C++,Shared Ptr,我有个问题。我想将共享的ptr指向存储在类中的对象。代码中有一个Holder::getSomething函数,它返回对基的引用。我想把它转换成派生的b_ptr。代码如下: #include <memory> using namespace std; class A{ public: int a; A() : a(0){} virtual ~A(){} }; class B : public A { public: bool b; B()

我有个问题。我想将共享的ptr指向存储在类中的对象。代码中有一个Holder::getSomething函数,它返回对基的引用。我想把它转换成派生的b_ptr。代码如下:

#include <memory>
using namespace std;

class A{
public:
    int a;

    A() : a(0){}
    virtual ~A(){}
};

class B : public A {
    public:
    bool b;

B() : A(){ b = false; }
};

class Holder{
public: 
    B arr[1];

    // there's an A ref here, not B, because i'll have a boatload of deriveds. 
    A& getSomething(){
        return arr[0];
    }

    Holder(){
        arr[0] = B();
    }
};

int main(){ 

Holder h;

shared_ptr<B> b_ptr;

// b_ptr = something_alien_here(h.getSomething());

return 0;
};
我知道,我的意思是我有一个未受过教育的猜测,我应该使用动态指针强制转换,但我找不到/弄明白正确的语法

如果您可以保证h的寿命比b_ptr长,那么您可以使用shared_ptr的借用构造函数,并使用cast:

Holder h;

std::shared_ptr<B> b_ptr(std::shared_ptr<B>(),
                         &static_cast<B&>(h.getSomething()));

现在b_ptr与临时的、空的共享指针共享所有权,其效果是永远不会为b调用删除器。这就是为什么现在您有责任确保指针存在至少只要共享指针可以被取消引用

一个共享指针的全部要点是它的ref被计数和析构函数 当最后一个超出范围时,它指向什么。你不希望发生这种事 另一个类的成员对象,因为这是未定义的行为


简言之;不要这样做。

如果您确定getSomething确实返回了对B的引用,那么B_ptr.resetstatic_cast&h.getSomething;。然而:a如果你知道这一点,那么你为什么不首先返回B&B,B为什么共享?当指针超出范围时,它将尝试删除指针,这会显示未定义的行为,并且可能会崩溃,因为指针没有分配新的。为什么首先需要指针?参考资料有用吗?