Search code examples
c++shared-ptrdecltype

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


Solution

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