我应该在什么时候删除std::smatch返回的std::字符串在一个正则表达式迭代器,如果有的话?



我是c++的新手,我一直在摆弄它的标准正则表达式库。我根据以下参考资料制作了这个概念搜索功能的证明。https://en.cppreference.com/w/cpp/regex/regex_iterator
这段代码编译得很好,并按预期运行,但是回顾起来,我担心有几个地方可能会导致一些内存泄漏。
如何处理库调用的字符串返回值?你是否将它们复制到new创建的字符串对象中?还是像对待值一样对待它们,从不担心内存分配?

我知道make_uniquemake_shared是很好的选择,但当我对c++内存管理结构(如调用析构函数等)的理解仍然不稳定时,我不太愿意使用它们。

#include <iostream>
#include <string>
#include <regex>
#include <vector>
//a proof of concept function that returns regex match strings
std::vector<std::string> return_matches(std::string str){
std::regex reg("[0-9]+");
std::vector<std::string> result;

auto i = std::sregex_iterator(str.begin(), str.end(), reg);
auto str_end = std::sregex_iterator();

for(i; i != str_end; ++i ){
std::smatch match = *i;
result.push_back(match.str());
//string returned from match.str() will be shallow copied into the result array
//but at the same time, the string seems like to be going out of the scope,
//does that mean its destructor is called and its internal (heap) memory
//gets freed?
}

return result;
//Same thing here, will the destructor be called for the vector object,
//leading to a memory leak
}
int main(){
std::string input = "hello 123 afsdha 554 asda 12 721";
auto result = return_matches(input);

//printing the result
for(int i = 0; i < result.size(); i++){
std::cout << result[i] << std::endl;
}
}

我应该在什么时候删除std::smatch返回的std::字符串在一个正则表达式迭代器,如果有的话?

只能删除指针。更具体地说,您可以删除由(非放置)new表达式返回的指针。

match.str()不返回指针。它返回std::string的一个实例。您不需要,也不能删除std::string对象。

如何处理库调用的字符串返回值?

它是一个临时对象。无论您如何处理它,临时对象都会自动销毁。没有内存泄漏的风险。

您是否将它们复制到您自己的字符串…

当然,如果你想存储字符串以供以后使用,你可以这样做。

…这是由新创建的吗?

。这种方式存在内存泄漏。几乎不需要使用new,甚至很少需要使用new来创建std::string实例。

或者你把它们当作值,从不担心内存分配?

是的。将值视为值

//does that mean its destructor is called

是的。临时对象在包含它的完整表达式的末尾被销毁。

//and its internal (heap) memory gets freed?

如果std::string分配了任何内存,它会负责释放它。

//Same thing here, will the destructor be called for the vector object,

是的,具有自动存储持续时间的对象将在声明它们的作用域结束时自动销毁。

//leading to a memory leak

没有;恰恰相反。由于析构函数释放了内存,所以没有泄漏。

最新更新