【问题标题】:Find a shared_ptr in an unordered_set with only a const shared_ptr?在只有一个 const shared_ptr 的 unordered_set 中找到一个 shared_ptr?
【发布时间】:2018-11-18 09:11:18
【问题描述】:

我有一个unordered_set<shared_ptr<T>> us,我想知道k 中是否有针us,但k 的类型为shared_ptr<T const>,所以unordered_set<shared_ptr<T>>::find 抱怨它无法转换。

有没有办法解决这个问题?也许通过直接提供哈希?

我确实尝试过const_cast(感觉很脏),但这并没有成功。

【问题讨论】:

  • 不确定这个....shared_ptr<T>shared_ptr<T const> 可以拥有同一个对象,您不会有 2 个不同对象类型的所有者块吗?
  • @RichardCritten 从shared_ptr<T>shared_ptr<T const> 的隐式转换是正确的。而且,您甚至可以使用别名构造函数让shared_ptr<T>shared_ptr<int> 共享所有权。 (这可能被用来产生一个共享指针,指向一个由共享指针拥有的类的成员。当最后一个共享所有权的指针被销毁时,原始删除器被调用,忽略最后一个共享指针的类型。)

标签: c++ constants unordered-set


【解决方案1】:

在这里使用std::const_pointer_cast 是一种可能的解决方案。

us.find(std::const_pointer_cast<T>(k));

由于您没有修改k,所以丢弃 const 是可以的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2021-09-02
    相关资源
    最近更新 更多