Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do these std::string and c_str() pointer addresses match?

Tags:

c++

What magic does std::string perform when we take its address using &? The returned address matches the c_str() address. But we know the c_str() is a field somewhere inside the std::string, not the address of the std::string instance itself? How does it do that?

E.g. in this code, it prints "Equal" :

#include <string>
#include <iostream>

int main(int argc, char const *argv[])
{
    std::string s = "Hello, World!";
    auto addr = &s;
    auto addr2 = s.c_str();
    std::cout << std::hex << addr << std::endl;
    std::cout << std::hex << reinterpret_cast<const void*>(addr2) << std::endl;
    if ((void*)addr == (void*)addr2) {
        std::cout << "Equal" << std::endl;
    } else {
        std::cout << "Not equal" << std::endl;
    }
    return 0;
}
like image 389
Jose Fonseca Avatar asked Jan 21 '26 09:01

Jose Fonseca


1 Answers

std::string::c_str() (and std::string::data()) returns a pointer to the string's current character buffer, wherever it resides in memory.

The only way that pointer can be equal to the address of the std::string object itself is if the std::string implementation supports Short String Optimization (ie, character data of a very short length is stored directly in the string object itself, rather than elsewhere in dynamic memory), and the SSO buffer is the 1st data member of std::string. C++ guarantees that the 1st data member of an object is at the same address as the object itself.

But, there is no guarantee that the SSO buffer (if it exists) is the 1st data member. So, do not rely on this behavior.

like image 145
Remy Lebeau Avatar answered Jan 27 '26 00:01

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!