Mar*_*ius 5 c++ string stl temporary stream
以下部分演示了我的问题:( GCC上的编译错误)
stringstream ss;
string s;
ss << "Hello";
// This fails:
// s.swap(ss.str());
// This works:
ss.str().swap(s);
Run Code Online (Sandbox Code Playgroud)
我的错误:
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>]
Run Code Online (Sandbox Code Playgroud)
虽然我理解stringstream中的str()返回一个临时的,但它没有意义,并且我不应该立即明白我应该使用局部变量作为参数而不是我的第一直觉调用临时交换.
显然,直接赋值工作得更好,而较新的C++标准已经移动了完美的语义,但这些并不适用于我的实现.
Visual Studio因为放松了C++标准而没有出现这个问题.我有点已经理解了对临时事物的整个const引用(我假设是我编译错误的原因).
我的问题:任何人都可以向我解释这是否是唯一的解决方案,并且可能会向我解释将来如何考虑这个问题,以便我可以发现并解决类似的问题?
(如果没有人有任何有用的见解,我至少会在这里为有类似问题的人发帖)
您不能将临时绑定到非const引用.由于这个原因,临时返回的from ss.str()
不能传递到std::string::swap
期望修改其参数的那个(因此它需要使用它的参数non-const&
).
第二个版本的工作原理是您在允许的临时对象上调用成员函数.
但是你为什么要先换掉?通常,一个简单的:
std::string s(ss.str());
Run Code Online (Sandbox Code Playgroud)
应该足够好.这并不比交换效率低(至少在带有移动语义的C++ 0x中),但同时更具可读性.
在使用了 swap-with-temporary 惯用法足够多次之后,像这样的行
std::vector<int>().swap(v); // clear and minimize capacity
Run Code Online (Sandbox Code Playgroud)
或者
std::vector<int>(v).swap(v); // shrink to fit
Run Code Online (Sandbox Code Playgroud)
这似乎并不那么不合时宜。将 swap 作为临时对象的成员函数来调用是很正常的。当然,正如已经提到的,使用交换来填充默认构造的字符串而不是使用复制构造函数并不是那么惯用。
归档时间: |
|
查看次数: |
1619 次 |
最近记录: |