3.18. C++
...then we can see that the compiled code is just the same as in the pointers example (3.21 on page 611):
Listing 3.100: Optimizing MSVC 2010
_x$ = 8 ; size = 4
_y$ = 12 ; size = 4
_sum$ = 16 ; size = 4
_product$ = 20 ; size = 4
?f2@@YAXHHAAH0@Z PROC ; f2
mov ecx, DWORD PTR _y$[esp-4]
mov eax, DWORD PTR _x$[esp-4]
lea edx, DWORD PTR [eax+ecx]
imul eax, ecx
mov ecx, DWORD PTR _product$[esp-4]
push esi
mov esi, DWORD PTR _sum$[esp]
mov DWORD PTR [esi], edx
mov DWORD PTR [ecx], eax
pop esi
ret 0
?f2@@YAXHHAAH0@Z ENDP ; f2
(The reason why C++ functions has such strange names is explained here:3.18.1 on page 542.)
Hence, C++ references are as much efficient as usual pointers.
3.18.4 STL.
N.B.: all examples here were checked only in 32-bit environment. x64 wasn’t checked.
std::string
Internals
Many string libraries [Dennis Yurichev,C/C++ programming language notes2.2] implement a structure
that contains a pointer to a string buffer, a variable that always contains the current string length (which
is very convenient for many functions: [Dennis Yurichev,C/C++ programming language notes2.2.1]) and
a variable containing the current buffer size.
The string in the buffer is usually terminated with zero, in order to be able to pass a pointer to the buffer
into the functions that take usual CASCIIZstrings.
It is not specified in the C++ standard how std::string has to be implemented, however, it is usually
implemented as explained above.
The C++ string is not a class (as QString in Qt, for instance) but a template (basic_string), this is made in
order to support various character types: at leastcharandwchar_t.
So, std::string is a class withcharas its base type.
And std::wstring is a class withwchar_tas its base type.
MSVC
The MSVC implementation may store the buffer in place instead of using a pointer to a buffer (if the string
is shorter than 16 symbols).
This implies that a short string is to occupy at least16 + 4 + 4 = 24bytes in 32-bit environment or at least
16 + 8 + 8 = 32
bytes in 64-bit one, and if the string is longer than 16 characters, we also have to add the length of the
string itself.
Listing 3.101: example for MSVC
#include
#include <stdio.h>