3

この最小限の例を考えると。

#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++ を使用したため、ムーブ コンストラクターであってはなりません。

この動作を無効にするにはどうすればよいですか?

4

3 に答える 3

6

戻り値の最適化は、ローカル オブジェクト (関数内)に影響sします。str_returnあなたは決してそれを計測しません。

文字列オブジェクト自体が動的メモリを管理し、返されたときにその管理されたメモリを次の文字列に渡すことを選択します。あなたが計装しているのは、その管理されたメモリです。当たり前ですが、それは変わりません。

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);
}
于 2013-11-06T08:33:47.113 に答える