【问题标题】:LLVM find_if implicitly-deleted copy constructor with unique_ptr<>LLVM find_if 使用 unique_ptr<> 隐式删除的复制构造函数
【发布时间】:2014-04-14 22:37:22
【问题描述】:

因此,我正在阅读一本关于使用 SFML 和 C++11 进行游戏开发的书,其中用于创建场景树的代码行给我带来了一些麻烦,这在我看来是有点过头了。由于 find_if 算法中 unique_ptr 的复制构造函数隐式删除,编译器返回错误。

这是带有 find_if 调用的函数。 Ptr 是std::unique_ptr&lt;SceneNode&gt; 的类型定义。这是我目前唯一使用 find_if 的地方。

SceneNode::Ptr SceneNode::detachChild(const SceneNode& node) {
    auto found = std::find_if(mChildren.begin(), mChildren.end(), [&] (Ptr p) -> bool { return p.get() == &node; });

    assert(found != mChildren.end());

    Ptr result = std::move(*found);
    result->mParent = nullptr;
    mChildren.erase(found);
    return result;
}

返回的错误是在算法本身中提出的,具体来说是“调用 'Ptr' 的隐式删除的复制构造函数。”

Call to implicitly deleted copy constructor in LLVM 有一个相关问题,但在我的情况下,答案没有多大意义。

请注意,我正在使用最新的 Xcode 5 版本进行开发。

【问题讨论】:

    标签: c++ xcode c++11 llvm unique-ptr


    【解决方案1】:

    find_if 调用中的 lambda 表达式采用 valuePtr(又名unique_ptr&lt;SceneNode&gt;)参数,这意味着它正在尝试复制unique_ptrunique_ptrs 不可复制,因此出现错误。

    将 lambda 表达式更改为以下内容:

    [&] (Ptr const& p) -> bool { return p.get() == &node; }
    //       ^^^^^^
    // take the argument by reference and avoid copying
    

    【讨论】:

    • 太棒了,效果很好!这是我第一次与 lambda 表达式交互,所以我直接从书中借用了这句话。似乎是时候阅读更多关于它们的信息了。
    • @gelliott181 另一个提示:您可以删除 -&gt; bool 部分,因为 C++11 允许编译器推断包含单个 return 语句的 lambda 表达式的返回类型,例如您拥有的那个.
    猜你喜欢
    • 2013-11-02
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多