不是的。
string f(bool x)
{
string s = "1111111111111111111111111111111111111111111111111111111111111";
if(x){
std::cout << "var address: " << &s << std::endl;
std::cout << "buf address: " << (void *)(s.data()) << std::endl;
return s;
}
return string("222222222222222222222222222222222222222222222222222222222222222");
}
string g(bool x)
{
const string s = "1111111111111111111111111111111111111111111111111111111111111";
if(x){
std::cout << "var address: " << &s << std::endl;
std::cout << "buf address: " << (void *)(s.data()) << std::endl;
return s;
}
return string("222222222222222222222222222222222222222222222222222222222222222");
}
string r()
{
const string s = "1111111111111111111111111111111111111111111111111111111111111";
std::cout << "var address: " << &s << std::endl;
std::cout << "buf address: " << (void *)(s.data()) << std::endl;
return s;
}
int main()
{
{
std::cout << "call f(true), expect move ctor" << std::endl;
string s = f(true);
std::cout << "var address: " << &s << std::endl;
std::cout << "buf address: " << (void *)(s.data()) << std::endl;
}
std::cout << "===============" << std::endl;
{
std::cout << "call g(true), expect copy ctor" << std::endl;
string s = g(true);
std::cout << "var address: " << &s << std::endl;
std::cout << "buf address: " << (void *)(s.data()) << std::endl;
}
std::cout << "===============" << std::endl;
{
std::cout << "call r(), expect NRVO" << std::endl;
string s = r();
std::cout << "var address: " << &s << std::endl;
std::cout << "buf address: " << (void *)(s.data()) << std::endl;
}
return 0;
}
$ g++ t.cpp -std=c++17
输出:
call f(true), expect move ctor
var address: 0x7fffc4ea36c0
buf address: 0x7fffbd418280
var address: 0x7fffc4ea3720
buf address: 0x7fffbd418280
===============
call g(true), expect copy ctor
var address: 0x7fffc4ea36c0
buf address: 0x7fffbd418280
var address: 0x7fffc4ea3720
buf address: 0x7fffbd4182d0
===============
call r(), expect NRVO
var address: 0x7fffc4ea3720
buf address: 0x7fffbd4182d0
var address: 0x7fffc4ea3720
buf address: 0x7fffbd4182d0
case-5对应的是g(true),你可以看到变量和buf地址都不一样。
【 在 libgcc 的大作中提到: 】
: 为什么我试了下case5是move的?
: string的data()返回的地址是一样的
:
--
FROM 209.249.20.*