Skip to content

Commit

Permalink
Fixes the initialization of fixed_address_empty_string
Browse files Browse the repository at this point in the history
This makes `fixed_address_empty_string` a function returning a static instance.
It avoids the static-initialization fiasco that can happen when using a global static variable.

Resolves: protocolbuffers#8129
  • Loading branch information
danieljoos committed Dec 9, 2020
1 parent 26c0fbc commit d27fab6
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
12 changes: 6 additions & 6 deletions src/google/protobuf/generated_message_util.cc
Expand Up @@ -72,15 +72,15 @@ void DestroyString(const void* s) {
static_cast<const std::string*>(s)->~basic_string();
}

PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT
PROTOBUF_ATTRIBUTE_INIT_PRIORITY EmptyString
fixed_address_empty_string; // NOLINT

PROTOBUF_CONSTINIT const EmptyString& fixed_address_empty_string() {
PROTOBUF_CONSTINIT static const EmptyString emptyStringInstance;
return emptyStringInstance;
};

PROTOBUF_CONSTINIT std::atomic<bool> init_protobuf_defaults_state{false};
static bool InitProtobufDefaultsImpl() {
::new (static_cast<void*>(&fixed_address_empty_string.value)) std::string();
OnShutdownDestroyString(&fixed_address_empty_string.value);
::new (static_cast<void*>(&fixed_address_empty_string().value)) std::string();
OnShutdownDestroyString(&fixed_address_empty_string().value);

// Verify that we can indeed get the address during constant evaluation.
PROTOBUF_CONSTINIT static const std::string& fixed_address_empty_string_test =
Expand Down
5 changes: 2 additions & 3 deletions src/google/protobuf/message_lite.h
Expand Up @@ -165,11 +165,10 @@ union EmptyString {

// Default empty string object. Don't use this directly. Instead, call
// GetEmptyString() to get the reference.
PROTOBUF_EXPORT extern EmptyString fixed_address_empty_string;

PROTOBUF_EXPORT extern const EmptyString& fixed_address_empty_string();

PROTOBUF_EXPORT constexpr const std::string& GetEmptyStringAlreadyInited() {
return fixed_address_empty_string.value;
return fixed_address_empty_string().value;
}

PROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const std::string& str);
Expand Down

0 comments on commit d27fab6

Please sign in to comment.