gpt4 book ai didi

c++ - 使用 unique_ptr 保护析构函数

转载 作者:行者123 更新时间:2023-11-30 01:34:27 26 4
gpt4 key购买 nike

我正在尝试从第三方库调用 API。

当我想对具有 protected 析构函数的类使用 unique_ptr 时出现问题。

这是例子,

#include <memory>
#include <iostream>

using namespace std;

class Parent {
public:
Parent () //Constructor
{
cout << "\n Parent constructor called\n" << endl;
}
protected:
~ Parent() //Dtor
{
cout << "\n Parent destructor called\n" << endl;
}
};

class Child : public Parent
{
public:
Child () //Ctor
{
cout << "\nChild constructor called\n" << endl;
}
~Child() //dtor
{
cout << "\nChild destructor called\n" << endl;
}
};

Parent* get() {
return new Child();
}

int main(int argc, char const* argv[])
{
Parent * p1 = get(); // this is ok
std::unique_ptr<Parent> p2(get()); // this is not ok
return 0;
}

我正在尝试将 unique_ptr 与父类一起使用。但是编译器抛出了错误

/usr/include/c++/5/bits/unique_ptr.h: In instantiation 
of ‘void std::default_delete<_Tp>::operator()(_Tp*) const
[with _Tp = Parent]’:
/usr/include/c++/5/bits/unique_ptr.h:236:17: required
from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp
= Parent; _Dp = std::default_delete<Parent>]’
main.cpp:38:35: required from here
main.cpp:12:5: error: ‘Parent::~Parent()’ is protected
~ Parent() //Dtor
^
In file included from /usr/include/c++/5/memory:81:0,
from main.cpp:2:
/usr/include/c++/5/bits/unique_ptr.h:76:2: error: within
this context
delete __ptr;

关于解决这个问题有什么想法吗?我无法破解 Parent 和 Child 类,因为它们是第三方库的类。

最佳答案

你可以制作std::default_delete<Parent> Parent的 friend 修复该错误。你可能还想制作 ~Parent virtualdelete 时避免未定义的行为通过 Parent 获取派生类指针。

例如:

class Parent { 
friend std::default_delete<Parent>;
// ...
protected:
virtual ~Parent();
// ...

然而,Parent设计清楚地表明您不应该 delete通过Parent指针,这就是为什么析构函数是非公开的。阅读Virtuality了解更多详情:

Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.


你可能想引入另一个中间基类来解决这个问题:

class Parent { // Comes from a 3rd-party library header.
protected:
~Parent();
};

struct MyParent : Parent { // The intermediate base class.
virtual ~MyParent();
};

class Derived : public MyParent {};

std::unique_ptr<MyParent> createDerived() {
return std::unique_ptr<MyParent>(new Derived);
}

int main() {
auto p = createDerived();
}

关于c++ - 使用 unique_ptr 保护析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56377634/

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