我有一些多年来一直成功使用的代码来实现“变体类型对象”;也就是说,一个 C++ 对象可以保存各种类型的值,但只使用(大约)与最大可能类型一样多的内存。该代码在精神上类似于标记联合,除了它也支持非 POD 数据类型。它通过使用 char 缓冲区、放置 new/delete 和 reinterpret_cast<> 来完成这个魔术。
我最近尝试在 gcc 4.4.3 下编译这段代码(使用 -O3 和 -Wall),并收到很多这样的警告:
warning: dereferencing type-punned pointer will break strict-aliasing rules
根据我的阅读,这表明 gcc 的新优化器可能会生成“错误”代码,我显然希望避免这种情况。
我在下面粘贴了我的代码的“玩具版”;我可以对我的代码做些什么来使其在 gcc 4.4.3 下更安全,同时仍然支持非 POD 数据类型?我知道作为最后的手段,我总是可以使用 -fno-strict-aliasing 编译代码,但如果代码在优化下不会中断会很好,所以我宁愿不这样做。
(请注意,我想避免在代码库中引入 boost 或 C++0X 依赖项,因此虽然 boost/C++0X 解决方案很有趣,但我更喜欢更老式的东西)
#include <new>
class Duck
{
public:
Duck() : _speed(0.0f), _quacking(false) {/* empty */}
virtual ~Duck() {/* empty */} // virtual only to demonstrate that this may not be a POD type
float _speed;
bool _quacking;
};
class Soup
{
public:
Soup() : _size(0), _temperature(0.0f) {/* empty */}
virtual ~Soup() {/* empty */} // virtual only to demonstrate that this may not be a POD type
int _size;
float _temperature;
};
enum {
TYPE_UNSET = 0,
TYPE_DUCK,
TYPE_SOUP
};
/** Tagged-union style variant class, can hold either one Duck or one Soup, but not both at once. */
class DuckOrSoup
{
public:
DuckOrSoup() : _type(TYPE_UNSET) {/* empty*/}
~DuckOrSoup() {Unset();}
void Unset() {ChangeType(TYPE_UNSET);}
void SetValueDuck(const Duck & duck) {ChangeType(TYPE_DUCK); reinterpret_cast<Duck*>(_data)[0] = duck;}
void SetValueSoup(const Soup & soup) {ChangeType(TYPE_SOUP); reinterpret_cast<Soup*>(_data)[0] = soup;}
private:
void ChangeType(int newType);
template <int S1, int S2> struct _maxx {enum {sz = (S1>S2)?S1:S2};};
#define compile_time_max(a,b) (_maxx< (a), (b) >::sz)
enum {STORAGE_SIZE = compile_time_max(sizeof(Duck), sizeof(Soup))};
char _data[STORAGE_SIZE];
int _type; // a TYPE_* indicating what type of data we currently hold
};
void DuckOrSoup :: ChangeType(int newType)
{
if (newType != _type)
{
switch(_type)
{
case TYPE_DUCK: (reinterpret_cast<Duck*>(_data))->~Duck(); break;
case TYPE_SOUP: (reinterpret_cast<Soup*>(_data))->~Soup(); break;
}
_type = newType;
switch(_type)
{
case TYPE_DUCK: (void) new (_data) Duck(); break;
case TYPE_SOUP: (void) new (_data) Soup(); break;
}
}
}
int main(int argc, char ** argv)
{
DuckOrSoup dos;
dos.SetValueDuck(Duck());
dos.SetValueSoup(Soup());
return 0;
}