admin管理员组文章数量:1295874
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;
}
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;
}
Share
Improve this question
asked Feb 12 at 1:02
JF4JF4
4882 silver badges16 bronze badges
8
|
Show 3 more comments
1 Answer
Reset to default 15std::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.
本文标签: cWhy do these stdstring and cstr() pointer addresses matchStack Overflow
版权声明:本文标题:c++ - Why do these std::string and c_str() pointer addresses match? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741627209a2389153.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
sizeof(std::string)
(which is implementation-defined). Then assigns
to a string literal which has length greater than that size. You should observe that your code prints "Not Equal". – Peter Commented Feb 12 at 6:29