簡體   English   中英

C ++ 11將unique_ptr轉換為基類

[英]C++11 converting a unique_ptr to a base class

我有一個函數,它接受一些對象的矢量並過濾它,並需要返回轉換為基類的對象的過濾矢量。

class Base {
    // stuff
}

class Derived : public Base {
    // more stuff
}

// elsewhere...
vector<reference_wrapper<const unique_ptr<Base>>> do_something(const vector<unique_ptr<Derived>> &things) {
    vector<reference_wrapper<const unique_ptr<Base>>> a;

    for (const unique_ptr<Derived> &derived : things) {
        if (check(derived)) {
            a.push_back(derived);  // this obviously doens't work -
                                   // what should I put here?!

            // this does not work:
            // a.push_back(std::ref(derived.get()))
            // because derived.get() is an rvalue
        }
    }

    return a;
}

返回的向量不擁有任何原始對象 - 它們應該只是讀者。 原始對象將比返回的向量的壽命更長。

我沒看過評論,所以也許已經在那里回答了。 但是,通常,當向量不擁有任何指向成員時,不會使用對unique_ptr的引用 - 因為這表示,向量應該能夠使用unique_ptr執行某些事情,只有所有者可以。

完整觀察者的常用方法是使用原始指針(至少在observer_ptr位於標准庫中之前)。 約束是你永遠不會在那些指針上調用delete或任何其他與內存相關的操作(這是observer_ptr在設計時不允許的)。

所以你寫道:

auto do_something(vector<unique_ptr<Derived>> const&things)
{
    vector<Base *> a;

    for (auto& derived : things) {
        if (check(derived))
        {
            a.push_back(derived.get());
        }

    return a;
}

與您選擇對const unique_ptr的引用的情況進行簡短比較: unique_ptr接口中的可調用const函數由get()get_deleter()operator bool() 在這三個中,使用vector<Base *>方法,您可以get_deleter()調用get_deleter()的可能性。 但是,作為一個讀者,幾乎肯定不需要刪除器。

Scott Meyer(以及他的參考文獻)提供了一個稍微相關的討論,可能會引起人們的興趣: http//scottmeyers.blogspot.de/2014/07/should-move-only-types-ever-be-passed.html

暫無
暫無

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

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