要初始化
shared_ptr initialization
本文关键字:初始化 更新时间:2023-10-16
成员定义为
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
您需要从传递给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_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
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 在函数内部的声明中初始化数组,并在外部使用它
- 继承:构造函数,初始化C++11中基类的类C数组成员