c++ - 如何解释 g++ 警告

标签 c++ g++ compiler-warnings

当我试图编译以下代码时,我收到了一个非常奇怪的 g++ 警告:

#include <map>
#include <set>

class A {
public:

    int x;
    int y;

    A(): x(0), y(0) {}
    A(int xx, int yy): x(xx), y(yy) {}

    bool operator< (const A &a) const {
        return (x < a.x || (!(a.x < x) && y < a.y));
    }
};

struct B {
    std::set<A> data;
};

int
main()
{
    std::map<int, B> m;

    B b;

    b.data.insert(A(1, 1));
    b.data.insert(A(1, 2));
    b.data.insert(A(2, 1));

    m[1] = b;

    return 0;
}

输出:

$ g++ -Wall -W -O3 t.cpp -o /tmp/t
t.cpp: In function ‘int main()’:
t.cpp:14: warning: dereferencing pointer ‘__x.52’ does break strict-aliasing rules
t.cpp:14: warning: dereferencing pointer ‘__x.52’ does break strict-aliasing rules
/usr/lib/gcc/i686-redhat-linux/4.4.2/../../../../include/c++/4.4.2/bits/stl_tree.h:525: note: initialized from here

它对我来说没有任何意义。我应该如何解释它?我看不出发布的代码有什么问题。

忘记指定编译器细节:

$ gcc --version
gcc (GCC) 4.4.2 20091027 (Red Hat 4.4.2-7)

最佳答案

gcc 4.4 有一个错误,其中 std::map breaks 错误地警告 严格的别名规则。

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39390

您的代码是有效的 C++。严格别名仅允许使用 -O3 时默认启用的优化子集。

您的解决方案是使用 -fno-strict-aliasing 或不同版本的 gcc 进行编译。

如果您对什么是严格别名感到好奇,that has been asked here .

关于c++ - 如何解释 g++ 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1964463/

相关文章:

c++ - 使用 g++ 编译多个 .cpp 和 .h 文件。我做对了吗?

c++ - 与前向声明的类声明友元是否合法?

Emacs 口齿不清 : Generate compiler warnings

c++ - 在构造函数 C++ 中将指针传递给 self

c++ - 如何将二维数组传递给用户定义列数的函数?(C++)

c - 编译时出错

c# - 使用 'Microsoft.Office.Interop.Word._Document.Close'时编译时警告

c# - C# 中 OrderDictionary 的通用实现显示不明确的方法警告

c++ - 匹配 'max'的 'std::function<const int &(const int &, const int &)>'没有重载

c++ - 在另一个项目中使用模板函数作为 dll