2013-03-20 67 views
3

甲构件被定义为shared_ptr的初始化

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中,铿锵+ + 3.2,与--std = c + + 11

回答

6

您需要从您是类型中删除引用传递到make_shared。 下面应该工作:

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

大可读性更强!我会看看remove_reference是否有用! – 2013-03-20 19:48:53

4

的问题是,*exit_to类型是一个参考,你不能有一个shared_ptr一个参考。

你可以移除的参照,但不是发现由operator*返回类型,然后剥离它的参考,它可能更容易只要问一下shared_ptr它包含什么类型:

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

嵌套element_type是由shared_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

+0

我认为构造'decltype(node_knot.exit_to):: element_type'会违背使用decltype的目的,因为你假设(或添加了约束)node_knot.exit_to的类型有一个'element_type'成员,对于大多数所有STL类型都不是这样。你的第二个解决方案听起来不错其中一个观察,包括在typedef本身类型的名称类型贬值typedef不是它。 typedefs的好处是你可以改变你的string_array的底层容器类型为其他任何东西,而不用改变代码中的所有事件。 – 2013-03-20 19:35:18

+0

然而,将'_array'放在'string_array'中会违背目的,因为一旦底层类型发生变化,名称就不再反映类型。看到那个叫做匈牙利符号的可怕的东西,yuck:http://en.wikipedia.org/wiki/Hungarian_notation – 2013-03-20 19:36:13

+0

@Zadirion,所以使用'make_shared'不会假定'shared_ptr'?至于typedef,我一般同意,但这取决于对类型的要求。如果它可以是任何序列,将'array'放在名称中会有误导性,但如果它的设计要求是它具有某些字符串类型的连续元素,那么将其称为'string_array'就没问题,并且仍然可以工作如果将实现更改为'vector ',或者只是改为不同长度的数组。不知道更多的上下文,你不能说这个名字应该更通用。 – 2013-03-20 20:21:47

相关问题