簡體   English   中英

如何在構造函數中使用刪除器初始化 std::unique_ptr?

[英]How do I initialize a std::unique_ptr with a deleter in a constructor?

我正在嘗試將 C 庫原始指針包裝在 std::unique_ptr 中,並使用帶有 Deleter 的構造函數來調用庫免費 function。 為了設置原始指針,我必須在構造函數中進行一些設置,因此我無法在初始化列表中構造 unique_ptr。

。H

class Resampler {

public:
    Resampler(unsigned int baseSamplerate, unsigned int channels);
  
private:
    std::unique_ptr<SwrContext, decltype(&swr_free)> context{nullptr, nullptr};
};

.cpp

Resampler::Resampler(unsigned int baseSamplerate, unsigned int channels) : baseSamplerate(baseSamplerate), ratio(1.0), channels(channels) {

    int64_t channelLayout;
     ..

    SwrContext *ctx = swr_alloc_set_opts(nullptr,
                                         channelLayout,
                                         AV_SAMPLE_FMT_FLTP,
                                         baseSamplerate,
                                         channelLayout,
                                         AV_SAMPLE_FMT_FLTP,
                                         baseSamplerate,
                                         0,
                                         nullptr);

    context = std::unique_ptr<SwrContext, decltype(&swr_free)>(ctx, &swr_free);
    setRatio(1.0);
}

這不會在 IDE 中產生錯誤,但編譯器會抱怨:

 > error: cannot initialize a parameter of type 'SwrContext **' with an > lvalue of type 'std::__ndk1::unique_ptr<SwrContext, void > (*)(SwrContext **)>::pointer' (aka 'SwrContext *')
std::unique_ptr<SwrContext, decltype(&swr_free)> context{ nullptr };

std::unique_ptr<SwrContext, decltype(&swr_free)> context{};

不是有效的構造函數,並且

std::unique_ptr<SwrContext, decltype(&swr_free)> context;

生產

錯誤:“重采樣器”的構造函數必須顯式初始化沒有默認構造函數的成員“上下文”

那么有沒有辦法做到這一點,還是我應該將上下文作為原始指針並手動管理?

在這種情況下, std::unique_ptr<T>的刪除器必須是可調用的 object。 嘗試使用這樣的仿函數

struct swr_deleter
{
    void operator()(SwrContext* context)
    {
        if (context != nullptr)
        {
            swr_free(context);
        }
    }
}

然后您的std::unique_ptr將如下所示:

std::unique_ptr<SwrContext, swr_deleter> context;

暫無
暫無

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

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