繁体   English   中英

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

[英]Impossible to disable return value optimization for std::string?

鉴于这个最小的例子。

#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);
}

您可能没有遇到RVO。 观察到的行为可能是由GCC中std::string实现中使用的写入优化复制引起的。 因此,实际上可以运行复制构造函数,但不会复制分配的缓冲区。

我不能评论答案,所以我会在这里注意:如果你为你构造函数调用字符串s,然后你调用str_return - 地址将是不同的:

std::string s; // implicit constructor call
print_ptr( s );
s  = str_return( "suffix" );
print_ptr( s );
std::cout << std::endl;

输出将是:

ptr: 0x28fec4  // for the original s;
ptr: 0x28fec8  // for local variable in function str_return
ptr: 0x28fec4  // the address of s after call str_return didn't change

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM