【发布时间】:2021-02-05 01:46:12
【问题描述】:
我正在尝试将 C 库原始指针包装在 std::unique_ptr 中,并使用带有 Deleter 的构造函数来调用库释放函数。为了设置原始指针,我必须在构造函数中进行一些设置,因此我无法在初始化列表中构造 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;
生产
错误:'Resampler' 的构造函数必须显式初始化 没有默认构造函数的成员“上下文”
那么有没有办法做到这一点,还是我应该将上下文设为原始指针并手动管理?
【问题讨论】: