digit plumber
digit plumber

Reputation: 1172

shared_ptr initialization

A member is defined as

std::shared_ptr<std::array<std::string, 6> > exit_to;

which points to additional data shared among others. When try to initiate the pointer "exit_to". The correct way is

node_knot.exit_to = std::make_shared<std::array<std::string, 6> >();

But it's in another file and I'd like to keep the pointer type consistent, something like this:

node_knot.exit_to = std::make_shared<decltype(*node_knot.exit_to)>();

But won't compile:

 /usr/include/c++/4.6/bits/shared_ptr_base.h:798:54: error: '__p'
 declared as a pointer to a reference of type
 'std::array<std::basic_string<char>, 6> &'
         __shared_ptr(const __shared_ptr<_Tp1, _Lp>& __r, _Tp* __p)
                                                             ^ /usr/include/c++/4.6/bits/shared_ptr.h:93:31: note: in instantiation
 of template class
 'std::__shared_ptr<std::array<std::basic_string<char>, 6> &, 1>'
 requested here
     class shared_ptr : public __shared_ptr<_Tp>
                               ^ ../node_booker.h:757:20: note: in
 instantiation of template class
 'std::shared_ptr<std::array<std::basic_string<char>, 6> &>' requested
 here
                                                         n.exit_to = std::make_shared<decltype(*n.exit_to)>();

I'm under Ubuntu 12.10, clang++ 3.2, with --std=c++11

Upvotes: 3

Views: 1704

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171461

The problem is that the type of *exit_to is a reference, and you can't have a shared_ptr to a reference.

You could remove the reference, but instead of finding the type returned by operator* and then stripping the reference off it, it's probably easier to just ask the shared_ptr what type it contains:

node_knot.exit_to = std::make_shared<decltype(node_knot.exit_to)::element_type>();

The nested element_type is the type stored by the shared_ptr.

Another option would be to add a typedef to the class and use it consistently wherever you need it:

typedef std::array<std::string, 6> string_array;
std::shared_ptr<string_array> exit_to;

// ... 

node_knot.exit_to = std::make_shared<Node::string_array>();

This is a lot more readable than using decltype

Upvotes: 4

Ed Barbu
Ed Barbu

Reputation: 1649

You need to remove the reference from the type you are passing to make_shared. The following should work:

node_knot.exit_to = std::make_shared<std::remove_reference<decltype(*node_knot.exit_to)>::type>();

Upvotes: 6

Related Questions