我有一个方法被宣布为这样:
/*!
rief Removes the leading and trailing white space from a string.
param s The string to remove the white space from.
param white_chars Characters to be considered as whitespace.
*/
std::string Trim(const std::string &s, const std::string &white_chars = "
");
方法的定义并不令人感兴趣,但这里是:
std::string Trim(const std::string &s, const std::string &white_chars)
{
size_t startidx = s.find_first_not_of(white_chars);
if (startidx == std::string::npos) return "";
size_t endidx = s.find_last_not_of(white_chars);
return s.substr(startidx, endidx - startidx + 1);
}
现在,在大多数使用这种方法时,我只提出第一个论点。Valgrind给我以下警告:
==3338== 68 bytes in 2 blocks are possibly lost in loss record 4,639 of 7,212
==3338== at 0x4C2B1C7: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3338== by 0x728CA88: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==3338== by 0x728E2B4: char* std::string::_S_construct<char*>(char*, char*, std::allocator<char> const&, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==3338== by 0x728E414: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&, unsigned long, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==3338== by 0x728E441: std::string::substr(unsigned long, unsigned long) const (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==3338== by 0x6965F0A: str::Trim(std::string const&, std::string const&) (appbase.cpp:90)
==3338== by 0x5F481D7: netopt::Element::set_ID(std::string const&) (netopt_elem.cpp:85)
注意"路障可能丢失了"?我见过 Valgrind告诉我的"路障肯定是丢失了"
< 坚固 > 因此问题就变成, 我是不是通过给 std:: string & amp; code> 指定默认值来造成内存泄漏? 如果是这样, 我做错什么了? strong>