microsoft / microsoft/STL

<atomic>: In pre-C++20 mode, the constructor should be trivial

Open
#661 19 comments 6 reactions 0 assignees View on GitHub

A pull request for this has already been merged.

  • #694 by @AlexGuteniev — merged
bug
Dominant language
C++
Stars
11.1k
Forks
1.7k
Avg merge
4d 15h
Merged PRs (30d)
22

Description

Starting from VS 2019 16.6 (#336), std::atomic constructor is unconditionally initializing the value:

    constexpr atomic() noexcept(is_nothrow_default_constructible_v<_Ty>) : _Base() {}

Before this version. the constructor was trivial instead:

#ifdef __clang__ // TRANSITION, VSO-406237
    constexpr atomic() noexcept(is_nothrow_default_constructible_v<_Ty>) : _Base() {}
#else // ^^^ no workaround / workaround vvv
    atomic()                                  = default;
#endif // TRANSITION, VSO-406237

As far as I understand, this is a behavior change in C++20 standard. However, I would not expect to see this behavior without specifying /std:c++latest.

This is significant because it results in some cases where std::atomic in global scope now generates dynamic initializers. Notably, in this case:

struct Foo
{
    std::atomic<int> data[2];
};

Foo foo[2];

Before this change, the foo variable was placed into BSS with no dynamic initializer. After this change, the dynamic initializer is emitted. This is problematic because if any code in static constructors accesses the atomic, it may work on the atomic before it's initialized which means that the initialization will overwrite the value of the atomic to 0.

Thus this is a breaking change - which would be fine except that it's a silent breaking change, and I'd expect to have to opt into this change by using the latest standard version instead.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Review the constructor change shown in the issue alongside issue #336 and the closed pull request #694. Reproduce the global Foo array example in pre-C++20 mode and compare whether it receives a dynamic initializer; done means the constructor preserves the expected trivial behavior without requiring the latest language mode.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.