Pergunta

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);

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);

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

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);

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

Foi útil?

Solução

Use std::make_shared:

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

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

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?.

Outras dicas

Nname_pointer name (new Node_names (process));

Remark: This has nothing to do with shared_ptr, it would be the same with a regular pointer.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top