gpt4 book ai didi

c++ - 如何使用带有 std::unique_ptr 成员的自定义删除器?

转载 作者:IT老高 更新时间:2023-10-28 11:51:07 26 4
gpt4 key购买 nike

我有一个包含 unique_ptr 成员的类。

class Foo {
private:
std::unique_ptr<Bar> bar;
...
};

Bar 是具有 create() 函数和 destroy() 函数的第三方类。

如果我想在一个独立的函数中使用 std::unique_ptr,我可以这样做:

void foo() {
std::unique_ptr<Bar, void(*)(Bar*)> bar(create(), [](Bar* b){ destroy(b); });
...
}

有没有办法将 std::unique_ptr 作为类的成员?

最佳答案

假设 createdestroy 是具有以下签名的自由函数(这似乎是 OP 的代码片段的情况):

Bar* create();
void destroy(Bar*);

你可以这样写你的类Foo

class Foo {

std::unique_ptr<Bar, void(*)(Bar*)> ptr_;

// ...

public:

Foo() : ptr_(create(), destroy) { /* ... */ }

// ...
};

请注意,您不需要在此处编写任何 lambda 或自定义删除器,因为 destroy 已经是一个删除器。

关于c++ - 如何使用带有 std::unique_ptr 成员的自定义删除器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19053351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com