gpt4 book ai didi

c++ - 在 boost-variant 中调用匹配类型的析构函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:08:53 25 4
gpt4 key购买 nike

我正在使用 boost-variant,当在变体中切换类型时,我想确保调用析构函数。以下代码“有效”,但我不确定为什么。我觉得它应该是段错误,因为它在未初始化的指针上调用删除。幕后是否有一些 boost-variant 魔术?

#include <iostream>
#include <boost/variant.hpp>
using namespace std;

class A
{
public:
A() {}
virtual ~A() { cout << "Destructing A" << endl; }
};

class B
{
public:
B() {}
virtual ~B() { cout << "Destructing B" << endl; }
};

typedef boost::variant<A*, B*> req;

class delete_visitor : public boost::static_visitor<void>
{
public:
inline void operator() (A *a) const
{
cout << "Will destruct A" << endl;
delete a;
}
inline void operator() (B *b) const
{
cout << "Will destruct B" << endl;
delete b;
}
};
class Wrapper
{
public:
Wrapper(int s) {
setBackend(s);
}
virtual ~Wrapper() {
// cleanup
boost::apply_visitor(delete_visitor(), my_pick);
}
void setBackend(int s)
{
// make sure if we already have put something in our variant, we clean it up
boost::apply_visitor(delete_visitor(), my_pick);
if(s == 0)
my_pick = new A();
else
my_pick = new B();
}

private:
req my_pick;
};

int main()
{
Wrapper *w = new Wrapper(0);
w->setBackend(1);
delete w;
return 0;
}

以下是我得到的输出:

Will destruct A
Will destruct A
Destructing A
Will destruct B
Destructing B

最佳答案

根据 Boost doc对于 boost::variant:

"Never-Empty" Guarantee

All instances v of type variant guarantee that v has constructed content of one of the types Ti, even if an operation on v has previously failed.

查看“boost/variant.hpp”,特别是变体的默认构造函数,您会看到:

// boost/variant.hpp: 1383
variant()
{
// NOTE TO USER :
// Compile error from here indicates that the first bound
// type is not default-constructible, and so variant cannot
// support its own default-construction.
//
new( storage_.address() ) internal_T0();
indicate_which(0); // zero is the index of the first bounded type
}

对于有界的变体类型,第一个类型获得默认初始化。这意味着对于您的 req 类型,A * 获得零初始化。这也意味着 B * 是零初始化的,因为变体可以被视为 union 。

关于c++ - 在 boost-variant 中调用匹配类型的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17643088/

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