繁体   English   中英

shared_ptr初始化

[英]shared_ptr initialization

成员定义为

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

这表示其他人共享的其他数据。 当尝试启动指针“exit_to”时。 正确的方法是

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

但它在另一个文件中,我想保持指针类型一致,如下所示:

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

但是不会编译:

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

我在Ubuntu 12.10下,clang ++ 3.2,--std = c ++ 11

您需要从传递给make_shared的类型中删除引用。 以下应该有效:

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

问题是*exit_to的类型是引用,并且您不能将shared_ptr用于引用。

您可以删除引用,但不是找到operator*返回的类型,然后从中删除引用,而是可以更容易地询问shared_ptr它包含的类型:

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

嵌套的element_typeshared_ptr存储的类型。

另一个选择是在类中添加一个typedef ,并在需要的地方一致地使用它:

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

这比使用decltype更具可读性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM