0
#include <iostream>
#include <string>
#include <string_view>
using namespace std;

int main() {
    string a = "abcdef";
    cout << (const int*)a.c_str() << endl;//0x64fe20
    string_view av{ a };
    cout << av << endl;//abcdef

    string b = std::move(a);
    cout << (const int*)b.c_str() << endl;//0x64fdf0
    cout << av << endl;// bcdef
}

Possible output:

0x64fe20
abcdef
0x64fdf0
 bcdef

All the point of b = std::move(a) is to avoid copy.

We can see the string_view is bcdef and since the entire string is on b, so the string is must be copied (at least part of it), right?

And we can see the inner string buffer a.c_str() and b.c_str() are different. Ok, you can see C++ doesn't guarantee the buffer is same, but how to implement it without copying?

I tested on both VS2022 and GCC(I forget the version) with C++20 standard.

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • .c_str() might also not be doing what it thinks you are doing. From [std::string::c_str](https://en.cppreference.com/w/cpp/string/basic_string/c_str) : `Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.` (it is not required to return the internal data of the string, it can/will return a copy with an extra null terminator) – Pepijn Kramer May 24 '23 at 08:00
  • 9
    Try with a longer string and google "short string optimization". – Nelfeal May 24 '23 at 08:01
  • 1
    Just accept that there's a optimization happending for strings that are short enough. (Storing the data as part of the object itself instead of a dynamically allocated string.) If a dynamic allocation did happen, the ownership of the memory would be transferred by the move operation. – fabian May 24 '23 at 08:02
  • 1
    The second `cout << av << endl;` is undefined behavior. You get "\0bcdef" just lucky. – 273K May 24 '23 at 08:06
  • @Nelfeal, I guessed so, haha! – Zhang May 24 '23 at 08:30
  • @Nelfeal Consider posting as answer. – Minxin Yu - MSFT May 24 '23 at 09:34
  • @MinxinYu-MSFT Too lazy to elaborate. If anything, I'd mark this as a duplicate of https://stackoverflow.com/questions/10315041/meaning-of-acronym-sso-in-the-context-of-stdstring. I didn't because the question is quite different, even it answers OP's question. – Nelfeal May 24 '23 at 09:56
  • @Nelfeal, I tried a much longer string, you are right, the c_str()s became same! – Zhang May 24 '23 at 10:17
  • @PepijnKramer I believe that's not true in C++11 or later. The same page says `c_str() and data() perform the same function.`, and the page for [`data`](https://en.cppreference.com/w/cpp/string/basic_string/data) says it `returns a pointer to the underlying array serving as character storage`. I also found [this](https://timsong-cpp.github.io/cppwp/n4861/string.accessors#1). – Nelfeal May 24 '23 at 12:39

0 Answers0