解除引用end()是否安全? [英] Is it safe to dereference end()?
本文介绍了解除引用end()是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数具有以下签名:
std :: string f(const char * first,const char * last){
std :: string result;
std :: for_each(first,last,some_lambda_which_appends_to_result);
return result;
}
和std :: string的重载调用它:
std :: string f(const std :: string s){
。但是,您可以使用
return f(& * s.begin(), & * s.end());
//下面的例子假设字符串不为空
// f(& s.front(),& s.front()+ s.size());但是,这可能是不安全的(取消引用s.end()可能是一个错误,可能是一个错误。红牌犯罪本身)。
有一个安全的方法来获得一个指向字符开头的指针和一个过去的指针(如果是空字符串,两个空指针将会很好),
或do I必须写std :: string(const std :: string& s){
return s.empty )? strd :: string():f(& s.front(),& s.front()+ s.size());
}
解决方案code> end()
c_str()
或data()
来实现所需:std :: string(const std :: string& s){
return f(s.data(),s.data )+ s.size());
}
I have a function with the following signature:
std::string f(const char *first, const char *last) { std::string result; std::for_each(first, last, some_lambda_which_appends_to_result); return result; }
and an overload for std::string which calls it:
std::string f(const std::string s) { return f(&*s.begin(), &*s.end()); // The one below would assume that the string is not empty // f(& s.front(), & s.front() + s.size()); }
However, this may be unsafe (dereferencing s.end() might be a red card offense in itself). Is there a safe way to get a pointer to the beginning of characters and a one-past-the-end pointer (two null pointers would be fine in case of an empty string), or do I have to write
std::string(const std::string& s) { return s.empty() ? std::string() : f(& s.front(), & s.front() + s.size()); }
解决方案It's not safe to dereference
end()
. However, you can use eitherc_str()
ordata()
to achieve what you need:std::string(const std::string& s) { return f(s.data(), s.data() + s.size()); }
这篇关于解除引用end()是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文