gpt4 book ai didi

c++ - 无法禁用 std::string 的返回值优化?

转载 作者:太空狗 更新时间:2023-10-29 20:13:44 24 4
gpt4 key购买 nike

给定这个最小的例子。

#include <iostream>
#include <string>

void print_ptr(const std::string& s)
{
const char* data = s.data();
std::cout << "ptr: " << (void*)data << std::endl;
}

std::string str_return(const char* suffix)
{
std::string s("prefix");
s += " ";
s += suffix;
print_ptr(s);
return s;
}

int main()
{
std::string s = str_return("suffix"), t;
print_ptr(s);
t = str_return("suffix2");
print_ptr(t);
return 0;
}

我是这样编译的:

g++ -std=c++98 -fno-elide-constructors -g -Wall  str_return.cpp -o str_return

我的 g++:

gcc version 4.7.1

输出:

ptr: 0x804b04c
ptr: 0x804b04c
ptr: 0x804b07c
ptr: 0x804b07c

为什么指针仍然相等?

  • 它不应该是返回值优化——我把它关掉了
  • 它不应该是移动构造函数,因为我采用了非常古老的 c++ 标准

如何禁用此行为?

最佳答案

返回值优化会影响本地对象(str_return 函数中的 s)。你永远不会检测它。

字符串对象本身管理动态内存,并选择在返回时将管理的内存交给下一个字符串。您要检测的是 托管内存。很明显,这不会改变。

如果你真的想看到 RVO 的效果,检测本地对象:

#include <iostream>
#include <string>

void print_ptr(const std::string& s)
{
std::cout << "ptr: " << static_cast<const void *>(&s) << std::endl;
}

std::string str_return(const char* suffix)
{
std::string s("prefix");
s += " ";
s += suffix;
print_ptr(s);
return s;
}

int main()
{
std::string s = str_return("suffix");
print_ptr(s);
std::string t = str_return("suffix2");
print_ptr(t);
}

关于c++ - 无法禁用 std::string 的返回值优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19807201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com