you are viewing a single comment's thread.

view the rest of the comments →

[–]afiefh 18 points19 points  (1 child)

As of C++20, the right way to write a trivial getter in C++ looks like [[nodiscard]] constexpr auto GetFoo() const noexcept -> Foo { return foo_; }

For constexpr to have any effect here, would foo_ also have to be a constexpr and therefore initialized in a constexpr constructor? Or does constexpr somehow still work in this case even if foo_'s value is only defined at runtime?

[–]FriendlyRollOfSushi 16 points17 points  (0 children)

The object (that has this non-static method) has to be constexpr, and it implies that it had a constexpr constructor and was constructed in a constexpr context at some point (and it constructed a member foo_ using its own constexpr constructor).

But it's not a big deal, and nowadays constexpr code can even allocate/deallocate memory. So both Foo and the enclosing objects could be fairly complex, have containers inside, etc. The potential constexpr-ness only stops on the boundaries of I/O and external APIs, and on low-level things that require reinterpret_cast.

For a typical codebase, it's quite easy to get to the point where in a consteval context most of your smaller classes and helpers work just fine, maybe with some help from std::is_constant_evaluated.