Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of macros in std::string source

Tags:

c++

string

std

I'm writing some c++ code that makes use of std::string.
I wanted to see how to code is written, so I went into the source code. (ctrl + left click).
I noticed, that there are macros everywhere.
The code even ends with:

_STD_END
// Corresponds to: #define _STD_END }

I get why macros are useful, and I use them for my own Log.hpp file, but I don't understand why anyone would use macros such as _STD_END instead of just writing }.

Just to clear up, my question is why he author of std::string, P.J. Plauger, decided to use macros in this way, and if I also should?

like image 244
Xerxes Avatar asked Feb 28 '19 20:02

Xerxes


People also ask

How do you define a string macro?

We can create two or more than two strings in macro, then simply write them one after another to convert them into a concatenated string. The syntax is like below: #define STR1 "str1" #define STR2 " str2" #define STR3 STR1 STR2 //it will concatenate str1 and str2.

Why do we use std :: string?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

What is __ Cplusplus macro?

__cplusplus. This macro is defined when the C++ compiler is in use. You can use __cplusplus to test whether a header is compiled by a C compiler or a C++ compiler. This macro is similar to __STDC_VERSION__ , in that it expands to a version number.

What is __ LINE __?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.


Video Answer


1 Answers

That’s the Dinkumware library, which Microsoft licenses (although they've recently taken over full maintenance of their version). The _STD_BEGIN and _STD_END macros are used for customizing the std namespace. Some compilers don't (didn't?) support namespaces; for those compilers, the macro expansions are empty. Some compilers need some indirection, and those macros expand into directives that put the code into an implementor-specific namespace (i.e., a namespace whose name begins with an underscore followed by a capital letter), which may or may not be complemented by a using-directive to pull the contents of that namespace into std. And in many cases they expand into the obvious, ordinary namespace std { and }, respectively.

In short, they're about configurability for a multi-platform library implementation.

I worked for Dinkumware for quite a few years, so I have first-hand knowledge.

like image 196
Pete Becker Avatar answered Oct 20 '22 15:10

Pete Becker