这个 GCC 12.1 const 问题是错误还是功能?“尝试使用 const 对象调用非常量函数”

Rob*_*b L 53 c++ gcc gcc12

我们发现在 GCC 11.3 和 Visual Studio 2022 中成功编译的 C++ 代码在 GCC 12.1 中存在问题。代码位于编译器资源管理器上: https: //godbolt.org/z/6PYEcsd1h (感谢@NathanPierson 对其进行了一些简化。)

基本上,模板类决定尝试在 const 函数中调用非常量基类函数,即使 const 重载可用。这似乎是某种编译器错误,但也可能是一些我不明白的奇怪的新 C++ 规则。这是否代表编译器错误?

struct BaseClass
{
    // Commenting this non-const function out will also fix the compilation.
    int* baseDevice() { return nullptr; }
    const int* baseDevice() const { return nullptr; }
};

template <class ObjectClass>
struct DerivedClass : BaseClass
{

};

template <class ObjectClass>
struct TopClass : DerivedClass<ObjectClass>
{
  public:
    virtual int failsToCompile() const
    {
      // This should choose to call the const function, but it tries to call the non-const version.
      if (BaseClass::baseDevice())
         return 4;

      return 1;
    }
};

int main()
{
    TopClass<int> x;
}
Run Code Online (Sandbox Code Playgroud)
struct BaseClass
{
    // Commenting this non-const function out will also fix the compilation.
    int* baseDevice() { return nullptr; }
    const int* baseDevice() const { return nullptr; }
};

template <class ObjectClass>
struct DerivedClass : BaseClass
{

};

template <class ObjectClass>
struct TopClass : DerivedClass<ObjectClass>
{
  public:
    virtual int failsToCompile() const
    {
      // This should choose to call the const function, but it tries to call the non-const version.
      if (BaseClass::baseDevice())
         return 4;

      return 1;
    }
};

int main()
{
    TopClass<int> x;
}
Run Code Online (Sandbox Code Playgroud)

Ted*_*gmo 60

这是 gcc 12.1 const 问题是错误还是功能

这是一个错误。我提交了一份错误报告,并且该问题已通过此提交得到验证。

票证已分配,解决方案的目标里程碑是版本 12.2 - 因此我们希望能快速修复。