初始化 shared_ptr ,当对象需要默认构造函数时 [英] Initialising shared_ptr , when the object requires a default constructor

查看:76
本文介绍了初始化 shared_ptr ,当对象需要默认构造函数时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了将 shared_ptr 分配给柠檬图形库中的图形类型变量,我这样做了:

For assigning shared_ptr to a Graph type variable in lemon graph library i did this:

typedef ListDigraph Graph;
typedef std::shared_ptr<Graph> Process_pointer;
Process_pointer process(new Graph);

它工作正常,但现在我需要为地图对象声明一个 shared_ptr,通常地图对象的工作方式如下:

It worked fine, but now i need to declare a shared_ptr for a map object, Normally the map object works like this :

Graph process;
typedef ListDigraph::NodeMap<string> Node_names;
Node_names name(process);

也就是说,name 的默认构造函数需要一个 Graph 对象.

That is, name requires a Graph object for its default constructor.

为了为它声明一个 shared_ptr,我这样做了:

For declaring a shared_ptr for it, i did this:

typedef ListDigraph::NodeMap<string> Node_names;
typedef std::shared_ptr<Node_names> Nname_pointer;
Nname_pointer name = new Node_names;
name(process);

我知道,name 的声明是错误的,但是我如何为其分配内存以及使用进程对象对其进行初始化.

I know, the declaration for name is wrong, but how do i assign it memory as well as initialise it with process object.

推荐答案

使用 <代码>std::make_shared:

auto p = std::make_shared<Node_names>(process);

这适用于具有任意数量参数的构造函数的类型.

This works for types with constructors with an arbitrary number of parameters.

请注意,这是使用托管对象创建 shared_ptr 的推荐默认方式.参见 为什么你几乎总是使用 make_shared 创建一个对象由 shared_ptrs 拥有?.

Note that this is the recommended default way to create shared_ptrs with managed objects. See Why should you almost always use make_shared to create an object to be owned by shared_ptrs?.

这篇关于初始化 shared_ptr ,当对象需要默认构造函数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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