2013-03-20 98 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