我如何查看std :: priority_queue的顶部<std :: unique_ptr <...>&gt;没有弹出也没有占有权

时间:2017-10-28 20:32:38

标签: c++ stl unique-ptr

下面粘贴了一些评论代码。我需要查看std::priority_queue<std::unique_ptr<...>>的顶部,但如果我调用.top(),我会收到编译错误:“尝试引用已删除的函数”。我知道我可以调用pop,但是我需要先根据值来做一些逻辑,以确定是否要弹出它。

struct MyStruct {
    int val = 2;

    MyStruct(const int val) : val(val) {}
};

void testDeque() {
    // This block won't compile because of call to q1.top()
    std::priority_queue<std::unique_ptr<MyStruct>> q1;
    q1.emplace(std::make_unique<MyStruct>(10));
    // How can I "peek" at the value at q1.top() without taking ownership of the unique_ptr?
    MyStruct* nonOwnershipPtr = DO_SOMETHING_MAGIC(q1.top());
    // At this point, the unique_ptr at t1.top() should still be there
}

1 个答案:

答案 0 :(得分:2)

这应该有效:

MyStruct* nonOwnershipPtr = q1.top().get();