c++ - 隐式转换产生 "error: taking address of temporary"(GCC vs clang)

标签 c++ compiler-errors g++ c++17 clang++

在试验强类型整数时,我遇到了一个来自 GCC 8.2 的奇怪错误:

error: taking address of temporary

我可以想象上述错误有意义的典型场景,但在我的情况下我没有遇到问题。重现错误的缩小(人为)示例如下:

#include <cstddef>

#include <type_traits>

enum class Enum : std::size_t {};

struct Pod {
  std::size_t val;

  constexpr operator Enum() const {
    return static_cast<Enum>(val);
  }
};

template<std::size_t N>
constexpr void foo() {
  using Foo = std::integral_constant<Enum, Pod{N}>;
  // [GCC] error: taking address of temporary [-fpermissive]
}

int main() {
  foo<2>();
}

为什么 GCC 8.2 在这里提示?Clang 6.0 很高兴(see goldbolt.org)。

请注意,GCC 的第二个错误可能有助于分析问题。我也不明白:

error: no matching function for call to Pod::operator Enum(Pod*)

GCC 8.2 读取的完整输出

<source>: In instantiation of 'constexpr void foo() [with long unsigned int N = 2]':

<source>:22:10:   required from here

<source>:17:50: error: taking address of temporary [-fpermissive]

   using Foo = std::integral_constant<Enum, Pod{N}>;

                                                  ^

<source>:17:50: error: no matching function for call to 'Pod::operator Enum(Pod*)'

<source>:10:13: note: candidate: 'constexpr Pod::operator Enum() const'

   constexpr operator Enum() const {

             ^~~~~~~~

<source>:10:13: note:   candidate expects 0 arguments, 1 provided

Compiler returned: 1

最佳答案

这显然是一个错误; 'Pod::operator Enum(Pod*)' 是胡说八道。您不能将参数传递给 operator Enum

编译器似乎认为在编译时将 Foo 转换为 Enum 的正确操作是 foo.operator Enum(&foo) 什么的。这都解释了“临时地址”和下一行。

关于c++ - 隐式转换产生 "error: taking address of temporary"(GCC vs clang),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52054316/

相关文章:

c++ - 共享常见对象 - 警告 "defined but not used"

c++ - 在 header 中声明指针? (C++)

c++ - VS2019 C++ 未知覆盖说明符

c++ - 让 constexpr 在 OSX 上的 C++17 中与 pow 一起使用

c++ - 如何找出使用 gcc 时实际应用了哪些优化?

c++ - Visual Studio 2008 糟糕的性能

c++ - 仅静态链接 boost 库 G++

c++ - 复制字符串集的正确方法是什么(在复制构造函数和赋值运算符中)?

c++ - g++ 4.9.0 允许我们使用带有布局分配的操作符delete[](void*, size_t)

jsp - 使用javax.crypto软件包的WSO2应用程序服务器5.0.1 JSP无法编译