Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot decide between different fmt::styles at runtime, gives crashes. #3625

Closed
TobiSchluter opened this issue Sep 5, 2023 · 1 comment
Closed

Comments

@TobiSchluter
Copy link
Contributor

TobiSchluter commented Sep 5, 2023

This crashes at runtime:

#include <fmt/core.h>
#include <fmt/color.h>

int main()
{
    auto quality = [&] {
        return fmt::styled(std::string_view("great"), fmt::emphasis::bold);
    };
    auto quality2 = quality();
    bool condition = false;
    auto quality3 = [&] {
        // Doesn't compile if this is uncommented.
        //if (condition) return fmt::styled("not great", fmt::emphasis::bold);
        return fmt::styled("great", fmt::emphasis::bold);
    }();

    // Either of the following two crashes at runtime
    fmt::print("result: {}\n", quality());
    //fmt::print("result: {}\n", quality2);

    // This works, but can only work for alternatives of the same length.
    fmt::print("result: {}\n", quality3);
}

https://godbolt.org/z/3cq9eWhnM

I'm only using the string_view here because in the real world I use multiple strings of different length which end up having different types when styled and thus can't be returned from a function as for quality3. It would be great if this or something equivalent worked, nice if the limitations were documented, good if there were a compiler error and bad (for me) if I'm just too dumb. A workaround is to format the quality flag before storing it of course, but that means formatting twice.

@vitaut
Copy link
Contributor

vitaut commented Sep 9, 2023

Storing the result of fmt::styled is unsafe and should be disallowed similarly to how it is done for other view-like APIs. Fixed in 5bdce18.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants