簡體   English   中英

傳遞unique_ptr <Derived> &到一個接受unique_ptr的函數 <Base> &

[英]Passing unique_ptr<Derived>& to a function accepting unique_ptr<Base>&

我需要通過引用一個函數來傳遞指向派生類的唯一指針,該函數接受對指向基類的唯一指針的引用,例如:

#include <memory>

using namespace std;

class Base {};
class Derived : public Base {};

void foo(std::unique_ptr<Base>& d){}

int main()
{
    unique_ptr<Derived> b = make_unique<Derived>();
    foo(b);
}
  1. 為什么此代碼不起作用? 我檢查了其他類似這樣的帖子,答案似乎是“因為C ++希望類型完全匹配”,但是為什么呢? 我可能造成什么危險情況?

  2. 如果我改為這樣做,它將編譯:

     void foo(unique_ptr<Base>&& d){} foo(move(b)); 

    這是合理的方法嗎?

我可能造成什么危險情況?

想象一下foo的以下實現:

void foo(std::unique_ptr<Base>& d){
    d.reset(new Base);
}

現在,您有一個std::unique_ptr<Derived>指向一個非Derived類型的對象,並且編譯器無法向您發出任何警告。

如注釋中所述,對您的問題的正確解決方案是按值獲取std::unique_ptr<Base> ,並將其移至調用站點。

void foo(std::unique_ptr<Base> d) {
    // move d to your list
}

int main() {
    unique_ptr<Derived> b = make_unique<Derived>();
    foo(std::move(b));
}

從派生到基礎的簡單static_cast,並進行適當的釋放調用(將資源的所有權轉移到新創建的指針)應該可以正常工作。

int main()
{
    unique_ptr<Derived> b = make_unique<Derived>();
    std::unique_ptr<Base> basePointer(static_cast<Base*>(b.release()));
    foo(basePointer);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM