117 points · by signa11 · 3y ago · 65 comments
unsigned char str[]{3,4,5,6,0};
std::stringstream ss;
ss << "str=" << str;
std::string text = ss.str();
> The content of text will be "str=♥♦♣♠".no, it wont. if you are on an old Windows with code page 437 then sure. but on any sane UTF-8 system, you're just going to get some binary data.
They dropped locale support for `std::to_chars` so hopefully they can be turned off for `std::format` too
Of course, it isn't able to do quite as much as a VM running in software (because fixed buffers for everything, etc.), but even so...
This question doesn't make sense for the context*. C++ is Ahead of Time, by design; there is nothing to "just in time" compile.
JIT (as a concept) only makes sense if you are, in some way, abstracting your code from native machine code (usually via some sort of VM, like Python or Java's), which the "system" languages (C, Rust, Zig, C++, etc) do not.
What I think you are trying to reference are "runtime optimizations"; in which case, the answer is probably no. Base and STD C++ are pretty conservative about what they put into the runtime. Extended runtimes like Windows' and glibc might do some conditional optimizations, however.
* Yes, some contrarian is going to point out a project like Cling or C++/CLI. This is why I'm being very clear about "context".
Can I talk to you about our Lord and Savior the CPU trace cache[1]?
That is to say, I know next to nothing about how modern CPUs are actually designed and hardly more about JITs, but a modern CPU’s frontend with a microop cache sure looks JITy to me. The trace cache on NetBurst looks even more classically JITy, but by itself it was a miserable failure, so meh.
In any event, a printf invocation seems like it should be too large for the cache to come into play;—on the other hand, all the predictors learning stuff over the iterations might make a meaningful impact?
Seems to me like that learning, if present, would make the benchmark less interesting, not more, as an actual prospective application of string formatting seems unlikely to go through formatting the same (kind of) thing and nothing else in a tight loop.
[1] https://chipsandcheese.com/2022/06/17/intels-netburst-failur...
This is clearly not what the OP was asking about.
I remember using variadic templates to print things in a single function call, like this:
int i; float f; string s;
print_special(i, f, s);
It would somehow imitate the behavior of python's print()I never really understood how variadic template worked, maybe one day I will, and to be honest, I'm suspecting it's really not very kind to compile time, it's a lot of type checks done under the hood.
It's a bit problematic that C++ cannot be compiled quickly without a fast CPU, I wonder how this is going to be addressed one day, because it seems that modules aren't a good solution to that, yet.
Another example would be convenient list comprehension, convenient maps wihout juggling around with tuples, first(), second(), at()...
For example, if you have a std::map<std::string, int>, you can iterate over it like this:
for (auto [s, n]: my_map) {
// s = string key, n = int value
}
You can test for membership: if (my_map.contains(“foo”)) { /* do something * }
Although I still usually use find because if the key is in the map, I probably want the value.You can use initialization lists with them too:
std::map<std::string, int> my_map = {
{ “one”, 1 },
{ “two”, 2 },
{ “three”, 3 }
}; for (auto [s, n]: my_map)
copies all the data needlessly, better to use for (const auto& [s, n]: my_map) to<vector>(items | filter(shouldInclude) | transform(f))
if you really want to, but generally C++ programmers prefer to be explicit and include the namespaces.(1) notation wise not very different from the old printf which is looked down upon.
(2) f"{name}'s hobby is {hobby} " would read like a novel and there a lot less comma seperated arguments.
(3) std::format is quite a lot of characters to type for something so ubiquitous.
Here’s the way I think about it. I don’t think I’m wrong but I’m absolutely open to being told otherwise.
C++ is a language. It has a standard library. The library depends on the language, but the language shouldn’t depend on the library. This is because many applications cannot use the standard library, or parts of it.
The conceptual issue with fstrings in C++ is that the formatting is done on a library level. An fstring would be a language feature. It wouldn’t be reasonable for syntax sugar to resolve to a library call.
So what we’d need is a way of having parameterised strings that the language knows to separate out into parameters in a function call. For instance:
f(f”Hello, {planet}”);
would resolve to:
f(“Hello, {}”, planet);
such that replacing f with std::format, std::print (C++23), fmt::format, fmt::print, spdlog::info, spdlog::error, or even scn::scan (?), would do exactly what you want.
However, the expression f”Hello, {planet}” would be meaningless on its own, and care would need to be taken to avoid:
std::string x = f”Hello, {planet}”;
from resolving to:
std::string x = “Hello, {}”, planet;
Which would be equivalent to
std::string x = planet;
Thanks to C++‘s ludicrous comma operator.
Disagree. Use whatever is the most simple and boring option for the problem's solution.
Also, the standard library has so much stuff that will give you pain in runtime, that avoiding sprintf really is not relevant.
I don't know what "Safe" means in general in the scope of C++. If there is a memory corruption, my program will crash. Then I will compile it with C++ debug runtime, which will pinpoint the exact location that caused the memory leak. Then I fix the leak.
Not using sprintf will not result in code that would not have memory leaks. C++ in total is unsafe. You need to write code and have production system that foremost takes this into account. You can't make C++ safe by following dogma of not using functions with possible side-effects. There is a very hight chance your fall-back algorithms themselves will leak memroy anyway.
The only way to write 'as non-leaky' C++ as possible is to make the code as simple, and easy to reason about as possible, and to have tooling to assist in program validation. This requirement is much more important than avoiding some parts of standard library.
Use static checkers, use Microsoft's debug C runtime, use address sanitizers, etc.
If you know some parts of you standard library are broken then ofc avoid them. But what can be considered "broken" really depends what one is trying to achiece, and which platforms one is targeting.
I will add, though, that I’ve found copilot to be very handy when it comes to generating formatting. Last week I used it while writing fmt::formatter specialisations for a library with 50 structs, some having over 20 members. Writing all of them took about 10 minutes. I dare say the same would hold for operator<< overloads.
It generates code that uses the class name and class members. In C++ we have no way of doing that (without hacky macro stuff).
Won't you face the same problem in Rust? If the library developer did not derive the Debug trait, you're out of luck.