首页 > 解决方案 > C++ 协议缓冲区:临时的非文字类型 'google::protobuf::internal::CallOnInitializedMutex' 在常量表达式中

问题描述

我从这里使用 protoc-3.18.0-win32 版本。成功编译.proto文件后,我的 QtCreator 5 (C++11) 程序中出现以下错误:

C:\Users\MyName\MyProject\lib\include\google\protobuf\stubs\mutex.h:124: error: temporary of non-literal type 'google::protobuf::internal::CallOnceInitializedMutex<std::mutex>' in a constant expression
In file included from lib\include/google/protobuf/descriptor.h:66:0,
                 from lib\include/google/protobuf/message.h:121,
                 from lib\include/google/protobuf/generated_message_bases.h:42,
                 from src/protodata/myfile.pb.h:26,
                 from src/myfile/myfile.h:12,
                 from src\myclass/myclass.h:8,
                 from src\mywidget.cpp:2:
lib\include/google/protobuf/stubs/mutex.h: In constructor 'constexpr google::protobuf::internal::WrappedMutex::WrappedMutex()':
lib\include/google/protobuf/stubs/mutex.h:124:29: error: temporary of non-literal type 'google::protobuf::internal::CallOnceInitializedMutex<std::mutex>' in a constant expression
   constexpr WrappedMutex() {}
                             ^
lib\include/google/protobuf/stubs/mutex.h:98:7: note: 'google::protobuf::internal::CallOnceInitializedMutex<std::mutex>' is not literal because:
 class CallOnceInitializedMutex {
       ^~~~~~~~~~~~~~~~~~~~~~~~
lib\include/google/protobuf/stubs/mutex.h:98:7: note:   'google::protobuf::internal::CallOnceInitializedMutex<std::mutex>' has a non-trivial destructor

其中错误的代码行是:

// Mutex is a natural type to wrap. As both google and other organization have
// specialized mutexes. gRPC also provides an injection mechanism for custom
// mutexes.
class GOOGLE_PROTOBUF_CAPABILITY("mutex") PROTOBUF_EXPORT WrappedMutex {
 public:
#if defined(__QNX__)
  constexpr WrappedMutex() = default;
#else
  constexpr WrappedMutex() {} // <--- Error points here
#endif

标签: c++c++11protocol-buffers

解决方案


尝试将高于 3.15.0 的 protobuf 版本与 gcc 7.3 和 c++17 一起使用时,我遇到了同样的问题。结果证明这是一个 gcc 错误,请参阅https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82461中的更多内容。

在查看 protobuf 生成的代码后,我发现在 3.15 之后的版本中,protobuf 生成的代码容器普遍存在“constexpr”,它触发了 gcc 错误。

可能的解决方案:

  1. 使用更高版本的 gcc,该错误在 7.4 中已修复(首选)
  2. 使用'-std=c++14'而不是'-std=c++17',这对我有用
  3. 使用早于 3.15、3.13 和 3.14 的 protobuf 对我有用。

推荐阅读