gpt4 book ai didi

c++ - 放置指向 shared_ptr 的多重映射的指针不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:09 24 4
gpt4 key购买 nike

vector 工作正常

Header
std::vector<std::shared_ptr<SceneNode>> subnodes_m;

Definition
void CompositeSceneNode::AddChild(SceneNode* subnode_p)
{
subnodes_m.emplace_back(subnode_p);
}

multimap 没有

Header
std::multimap<unsigned int, std::shared_ptr<SceneNode>> subnodes_m;

Definition
void CompositeSceneNode::AddChild(SceneNode* subnode_p, unsigned int layerIndex)
{
subnodes_m.emplace(layerIndex, subnode_p);
}

我收到以下错误:

error C2664: 'std::pair<_Ty1,_Ty2>::pair(const unsigned int &,const _Ty2 &)' :
cannot convert parameter 2 from 'RendererD3DWrapper::SceneNode *'
to 'const std::shared_ptr<_Ty> &'

有人知道吗?

最佳答案

你不能构建 std::pair<T1,T2>参数类型为 UV如果没有 U隐式转换进入T1 , 和 V进入T2 .在您的情况下,没有隐式转换 SceneNode*进入std::shared_ptr<SceneNode> .

来自 C++ 标准:

§ 20.3.2 Class template pair [pairs.pair]

template<class U, class V> constexpr pair(U&& x, V&& y);
  1. Requires: is_constructible<first_type, U&&>::value is true and is_constructible<second_type, V&&>::value is true.

  2. Effects: The constructor initializes first with std::forward<U>(x) and second with std::forward<V>(y).

  3. Remarks: If U is not implicitly convertible to first_type or V is not implicitly convertible to second_type this constructor shall not participate in overload resolution.

话虽如此,您无法初始化 std::pair<T1,T2>如下所示(因为 emplace 构建就地 一个 std::pair<key_type, mapped_type> 被称为 value_typestd::multimap ):

std::pair<unsigned int, std::shared_ptr<SceneNode>> p( 1, new SceneNode );

因为 std::shared_ptr<T> 的构造函数采用原始指针(在下面声明)是一个 explicit构造函数,因此您遇到的错误:

§ 20.9.2.2 Class template shared_ptr [util.smartptr.shared]

[...]

template<class Y> explicit shared_ptr(Y* p);

在 C++11 中,您应该或者构建一个 std::shared_ptr<T>打电话前 emplace :

subnodes_m.emplace(layerIndex, std::shared_ptr<SceneNode>(subnode_p));

您可以将参数转发给 pair 元素的构造函数(而不是将它们转发给 std::pair<T1,T2> 本身的构造函数),带有 piecewise construction :

subnodes_m.emplace(std::piecewise_construct
, std::forward_as_tuple(layerIndex)
, std::forward_as_tuple(subnode_p));

DEMO

Why does it work with std::vector of std::shared_ptr's then?

std::vector<std::shared_ptr<T>>::emplace_back成员函数转发 emplace_back 的参数到 std::shared_ptr<T> 的构造函数,满足显式上下文要求。如果是 map和一个 multimap , 放置的类型是 pair如果这些元素的参数类型和参数类型之间的转换不是隐式的(如上所述),它会禁用将参数进一步转发到其元素的构造函数。

关于c++ - 放置指向 shared_ptr 的多重映射的指针不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25991582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com