繁体   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