James S.
James S.

Reputation: 519

Visual Studio 2019 gives C26444 with cout.imbue

When I use Visual Studio 2019, it gives me the green squiggles with this:

#include <iostream>
#include <locale>

int main() {
    // Green squiggles given for this entire line:
    std::cout.imbue(std::locale("en_US.utf8"));
    // Visual Studio says, "C26444: Avoid unnamed objects with custom construction and destruction (es.84)"

    // Using cout.imbue to provide nice formatting for numbers:
    std::cout << "Example locale formatting:  " << 100'000.00 << '\n';
}

I've tried some variations like this:

std::locale my_locale("en_US.utf8");
// Now the green squiggles just appear from cout.imbue onward:
std::cout.imbue(my_locale);

I believe the es.84 is from the C++ Core Guidelines: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-noname

However, I'm not sure how to fix this. I looked at cppreference.com and cplusplus.com for examples, but I'm doing what they show.

What does Visual Studio not like and how can I fix it?

Upvotes: 1

Views: 351

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

The Visual Studio compiler (MSVC) doesn't 'like' the fact that you haven't named the return value of the call to imbue. Whether or not this warning is 'justified' is not for me to say; however, it is easy to add code to prevent the warning, by assigning the returned value to a named variable:

std::locale loc = std::cout.imbue(std::locale("en_US.utf8"));

Without this, the compiler assumes there is a call to the std::locale destructor on the unnamed (and otherwise unused) returned locale object (which there may well be).

Upvotes: 1

Related Questions