Ale*_*ato 7 c++ move-semantics c++11
鉴于这个例子:
std::vector<std::string> split(const std::string& str) {
std::vector<std::string> result;
std::string curr;
for (auto c : str) {
if (c == DELIMITER) {
result.push_back(std::move(curr)); // ATTENTION HERE!
} else {
curr.push_back(c);
}
}
result.push_back(std::move(curr));
return result;
}
Run Code Online (Sandbox Code Playgroud)
我可以重用curr
std:string吗?这段代码看起来很有效:在向量中curr
移动后result
,它变为空.我想确保这不是标准中未定义的行为,它只是因为运气而无法正常工作.
T.C*_*.C. 12
除了一些例外(例如,智能指针),移动的对象将保持有效但未指定的状态.
std::string
例如,在使用小字符串优化的情况下,如果字符串很小,则没有动态分配,移动是副本.在这种情况下,实现保持源字符串不受影响是完全有效的,并且不会产生清空字符串的额外成本.
归档时间: |
|
查看次数: |
2242 次 |
最近记录: |