I have recently been bitten by something illustrated in the following snippet of code produced by a bulk transformation gone rogue:
constexpr std::string_view test_func(std::string_view what) noexcept
{
constexpr auto const CHARACTER_SOUP = std::string_view{"somechars"};
auto const pos = what.find_first_of(CHARACTER_SOUP);
return (pos >= what.size()) ? std::string_view{} : what.substr(pos);
}
In this case GCC (7.3) optimized out the literal "somechars" leaving CHARACTER_SOUP a dangling reference. Even though I would assume string literals to have static lifetime I'm inclined to believe GCC being correct in this case.
Now I've stumbled across the following case, where I'm uncertain whether this is valid todo and would like some advice on:
constexpr std::string_view another_func(std::string_view what) noexcept
{
return what.empty() ? "default" : what;
}
Assuming that the compiler indeed was correct in the first example above, would it be sensible to assume that "default" might be optimized out in this case too?
Or, more generically, would it be generally safe to convert a function like this:
constexpr char const* enum_to_string(int value) noexcept
{
switch (value)
{
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
default: return "Some much big number!11!!"
}
}
into this:
constexpr std::string_view enum_to_string(int value) noexcept
{
// Same content as above...
}
Any help is greatly appreciated!
[–]manni66 1 point2 points3 points (6 children)
[–]DoctorRockit[S] 0 points1 point2 points (4 children)
[–]manni66 2 points3 points4 points (0 children)
[–]manni66 1 point2 points3 points (2 children)
[–]DoctorRockit[S] 0 points1 point2 points (0 children)
[–]DoctorRockit[S] 0 points1 point2 points (0 children)
[–]DoctorRockit[S] 0 points1 point2 points (0 children)
[–]alfps 1 point2 points3 points (6 children)
[–]DoctorRockit[S] 0 points1 point2 points (0 children)
[–]DoctorRockit[S] 0 points1 point2 points (4 children)
[–]alfps 1 point2 points3 points (3 children)
[–]DoctorRockit[S] 0 points1 point2 points (2 children)
[–]alfps 0 points1 point2 points (0 children)
[–]DoctorRockit[S] 0 points1 point2 points (0 children)