Question about using string :: swap () with temporary

The following segment demonstrates my problem: (compilation error in GCC)

stringstream ss;
string s;
ss << "Hello";

// This fails:
// s.swap(ss.str());

// This works:
ss.str().swap(s);

My mistake:

constSwap.cc:14: error: no matching function for call to 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >::swap(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
basic_string.tcc:496: note: candidates are: void std::basic_string<_CharT, _Traits, _Alloc>::swap(std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]

Although I understand that str () in stringstream returns a temporary value, it does not make sense and it did not immediately become obvious that I would have to call swap in a temporary place with a local variable as a parameter instead of my first instinct.

Obviously, direct assignment works better, and the new C ++ standards have movement semantics that are perfect, but they are not available for my implementation.

Visual Studio does not give this problem because it relaxes relative to the C ++ standard. I already understand that the whole constant refers to a temporary thing (which, I believe, is the cause of my compilation errors).

: - , , , , , , ?

( - , , , )

+5
3

, swap-time-time , ,

std::vector<int>().swap(v); // clear and minimize capacity

std::vector<int>(v).swap(v); // shrink to fit

. , swap - . , swap , , , .

+2

. , ss.str(), std::string::swap, ( , non-const&).

, - , .

? :

std::string s(ss.str());

. , ( , ++ 0x ), .

+7

, swap, , . . § 8.5.5, 5, :

§8.5.3 "cv1 T1" "cv2 T2" :

  • [bullet one, : -const ref]

  • const (.. cv1 const).

, , , - .

§3.10/10 lvalue , , , rvalue . [: -, (9.3), . ]

, , , , , , ( )

+1

All Articles