我可以为本地变量创建一个boost :: shared_ptr吗? [英] Can I create a boost::shared_ptr to a local variable?

查看:72
本文介绍了我可以为本地变量创建一个boost :: shared_ptr吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些引用给定对象的方法,有些则采用boost::shared_ptr.到目前为止,在我的测试方法中,我创建了一个shared_ptr指向这些对象之一,并将*ptr传递给需要引用的方法.是否有可能反过来做,例如在堆栈上创建一个本地对象,然后以一种安全的方式创建一个指向它的共享指针,从而可以用传统的指针找到&obj运算符的直接替代方案?

I have some methods that take a reference to a given object, and some are taking boost::shared_ptr. So far in my test method I created a shared_ptr pointing to one of these objects and pass *ptr to the methods expecting a reference. Is it possible to do it the other way round, e.g. create a local object on the stack, and then create a shared pointer to it in a safe way, to arrive at the straightforward alternative to &obj operator with traditional pointers?

推荐答案

#include <boost/shared_ptr.hpp>

void null_deleter(int *)
{}

int main()
{
    int i = 0;
    boost::shared_ptr<int> p(&i, &null_deleter);
}

这篇关于我可以为本地变量创建一个boost :: shared_ptr吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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