gpt4 book ai didi

c++ - 如果我在 C++ 中为类型为 "std::string &"的参数指定默认值,会导致内存泄漏吗?

转载 作者:IT老高 更新时间:2023-10-28 22:35:05 28 4
gpt4 key购买 nike

我有一个这样声明的方法:

/*!
\brief 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 = " \t\n\r");

方法的定义是无趣的,但无论如何都在这里:

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)

注意“ block 可能丢失”?我已经看到 Valgrind 告诉我“ block 肯定丢失了”的内存泄漏,但这是一个不太确定的消息。

所以问题就变成了,我是否通过为 std::string & 分配默认值而导致内存泄漏?如果是这样,我做错了什么?

最佳答案

没有技术问题,但在每次调用时从哲学上创建一个临时 std::string 并不是那么好。特别是对于 libstdc++(您似乎在使用),因为它每次都会导致内存分配(缺乏短字符串优化)。

由于 find_first_not_of 有一个采用 char const* 的重载,因此最好提供两个重载:

// First, the one with the default argument, but without a temporary
std::string Trim(std::string const& s, char const* white_chars = " \t\n\r");

// Second, for convenience, one with a `std::string`
std::string Trim(std::string const& s, std::string const& white_chars);

这也意味着在调用 Trim(xx, "abc") 时,您将避免生成临时 std::string :)

当然,矫枉过正的解决方案是重用已经编写的代码:Boost String Algorithm有许多字符串操作算法,包括trim .

关于c++ - 如果我在 C++ 中为类型为 "std::string &"的参数指定默认值,会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10750299/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com