How does std::forward work? [duplicate]

First, let’s take a look at what std::forward does according to the standard: §20.2.3 [forward] p2 Returns: static_cast<T&&>(t) (Where T is the explicitly specified template parameter and t is the passed argument.) Now remember the reference collapsing rules: (Shamelessly stolen from this answer.) And then let’s take a look at a class that wants to employ perfect forwarding: And now an example invocation: … Read more

How to debug ‘Stack smashing detected’?

If you read the website you will realize that this is a simple C++ wrapper over a C library. A typical issue with C library are buffer overruns: Try this program: Because the buffer can only contain 16 characters, the remaining characters will be written past its end. This is stack smashing, and undefined behavior. A number … Read more

std::string formatting like sprintf

Modern C++ makes this super simple. C++20 C++20 introduces std::format, which allows you to do exactly that. It uses replacement fields similar to those in python: Code from cppreference.com, CC BY-SA and GFDL Check out the compiler support page to see if it’s available in your standard library implementation. As of 2021-11-28, full support is only available in Visual Studio 2019 16.10, which … Read more

What does ‘\0’ mean?

C++ std::strings are “counted” strings – i.e., their length is stored as an integer, and they can contain any character. When you replace the third character with a \0 nothing special happens – it’s printed as if it was any other character (in particular, your console simply ignores it). In the last line, instead, you are printing a … Read more

C++ network programming

To understand sockets and use them right, you need The Sockets Bible: W. Richard Stevens, Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition) You absolutely must have this book before you sit down to write a line of sockets code. Don’t leave home without it. Really. Starting around $35 used at Amazon. EDIT: The OP asked about … Read more

Reading from text file until EOF repeats last line

Just follow closely the chain of events. Grab 10 Grab 20 Grab 30 Grab EOF Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven’t reached EOF because the EOF mark hasn’t been read yet (“binarically” speaking, its conceptual location is just after the 30 line). Therefore you … Read more