【问题标题】:Create std::pair or std::map with std::unique_ptr as value implicitely以 std::unique_ptr 作为值隐式创建 std::pair 或 std::map
【发布时间】:2016-06-24 23:10:37
【问题描述】:

此代码适用于 Visual Studio:

typedef struct {
    int a;
} data_t;

using datap_t = std::unique_ptr<data_t>;
using MyPair = std::pair<std::string, datap_t>;

int main() {
    data_t * pd1 = new data_t();
    MyPair p("tst", pd1); // This does not compile in gcc or clang
    // MyPair p2("tst", datap_t(pd1)); // This compiles

    return 0;
}

但是 clang 和 gcc 给出错误:

error: no matching function for call to 'std::pair<const std::basic_string<char>, std::unique_ptr<data_t> >::pair(const char [3], data_t*&)

Here 是可以尝试的理想人选。

我可以调用datap_t(pd1) 并且它编译的事实意味着构造函数是有效的,那么为什么该模板找不到合适的匹配?

我希望使用 emplace 将键值对添加到地图中,这就是为什么我希望首先进行这种隐式转换。请注意,与 Visual Studio 一样,隐式转换适用于大多数其他类型,例如 std::string 来自 "raw string"

This answer 看起来很相关,但它谈到了一个已修复的错误并且非常古老。

【问题讨论】:

  • 不要使用原始指针。 auto pd1 = std::make_unique&lt;data_t&gt;().
  • @kfsone 我没有,在处理外部 C 库时,处理原始指针是不可避免的。另外,我很想知道为什么这在 Visual Studio 中有效,而不是当叮当响,而不是寻找如何使它工作:)

标签: c++11 stdmap std-pair


【解决方案1】:

将单个原始指针作为输入的 std::unique_ptr 构造函数标记为 explicit 以防止隐式转换。

pd1 是一个原始指针。 MyPair p("tst", pd1); 涉及到 std::unique_ptr 的隐式转换,这就是为什么在 Clang 和 GCC 中编译失败的原因,应该是这样。您必须改用显式转换:

MyPair p("tst", datap_t(pd1));

更好的选择是根本不使用原始指针:

MyPair p("tst", std::make_unique<data_t>());

Clang 和 GCC 正在做正确的事情,而 Visual Studio 则不然(尽管它的 unique_ptr documentation 显示相关的构造函数是 explicit)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多