boost::optional<> 适用于简单的数据类型,但一旦用于从实现接口的类继承的类,当启用严格别名时它会失败。
例子:
#include <boost/optional.hpp>
struct MyLine{
double a;
double b;
};
class Edge{
public:
MyLine toMyLine() const;
private:
virtual MyLine doToMyLine() const =0;
};
class Wall:public Edge {
public:
Wall(MyLine const& seg):mMyLine(seg){};
private:
MyLine doToMyLine() const{return MyLine();};
MyLine mMyLine;
};
class SimpleWall {
public:
SimpleWall(MyLine const& seg):mMyLine(seg){};
private:
MyLine mMyLine;
};
int main(){
//boost::optional<Wall> res; //fails with strict aliasing error
boost::optional<SimpleWall> res2; //compiles just fine
}
使用 gcc 版本 4.4.3 编译以下错误:
g++ -c -pipe -Wall -Wextra -Wunused -Wmissing-declarations -Wpointer-arith -Wcast-align -Wwrite-strings -Wredundant-decls -Werror -std=c++0x -O2 -Wall -W -I/usr/local/boost_1_44_0 -o obj/main.o main.cpp
解决此问题的最佳方法是什么。我非常想启用严格混叠警告。我使用的是 boost 1.44 版。
更新:
变得更糟了!!考虑以下代码:
#include <boost/optional.hpp>
class MyBase{
public:
int toFoo() const;
private:
virtual int doToFoo() const =0;
};
class Child:public MyBase {
public:
Child(int const& foo):mFoo(foo){};
private:
int doToFoo() const{return 0;}
int mFoo;
};
int main(){
boost::optional<int> optint; //comment out for surprise
optint.get(); //comment out for surprise
boost::optional<Child> res2;
res2.get();
}
使用 gcc 版本 4.4.3 编译如下:
g++ -c -pipe -Wall -Wextra -Wunused -Wmissing-declarations -Wpointer-arith -Wcast-align -Wwrite-strings -Wredundant-decls -Werror -std=c++0x -O2 -Wall -W -I/usr/local/boost_1_44_0 -o obj/main.o main.cpp
如果标有“//comment out for surprise”的行被注释掉,我会收到严格的别名警告。我已经检查了至少 20 次。这是我见过的最奇怪的事情之一。看起来 boost::optional 初始化了某事。独立于它的模板参数,或者像 gcc 一样,只有在使用 sth 调用时才能理解 boost::optional。先琐碎。有任何想法吗 ?