1

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?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
James S.
  • 475
  • 3
  • 10
  • [https://social.msdn.microsoft.com/Forums/vstudio/zh-CN/ee71c16c-a53f-4d00-9a5d-0424b977031c/coutimbue-doesnt-affect-encoding-of-characters?forum=vclanguage](https://social.msdn.microsoft.com/Forums/vstudio/zh-CN/ee71c16c-a53f-4d00-9a5d-0424b977031c/coutimbue-doesnt-affect-encoding-of-characters?forum=vclanguage) – Suarez Zhou Jan 27 '20 at 07:46
  • @SuarezZhou-MSFT Thank you for the link. However, cout.imbue is working as desired in my case. I'm just trying to figure out how to eliminate the green squiggles. If the link explains how to do this, I'm not following. – James S. Jan 27 '20 at 13:48

1 Answers1

1

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).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • Thank you, that does the trick. Since all the examples on cppreference.com and cplusplus.com don't show this it makes me wonder if it's really necessary or the MSVC compiler is just worrying too much. I see there's an alternative: https://stackoverflow.com/questions/689677/why-cast-unused-return-values-to-void/53906625 So I could do: static_cast(std::cout.imbue(std::locale("en_US.utf8"))); I guess I'm not positive though if that doesn't cause a leak... – James S. Jan 27 '20 at 14:04