这段代码是否会导致内存泄漏 [英] Will this piece of code cause Memory Leak

查看:87
本文介绍了这段代码是否会导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是否会导致内存泄漏?



  #include   <   iostream  >  

使用 命名空间 std;

void someFunction( const char * str)
{
cout<< buffer:<< str<< ENDL;

std :: string abc(str);
abc = abc.substr( 5 );

cout<< 操作后:<< ENDL;

str = abc.c_str(); // 这会造成内存泄漏吗?
}

< span class =code-keyword> int main()
{
std :: string str = 我的文件就是这个;

const char * c = str.c_str();
cout<< c<< ENDL;
someFunction(c);
return 0 ;
}

解决方案

它不会泄漏 - 在C ++ 98中 c_str()缓冲区在对象被销毁时被清除,在C ++ 11中它是指向字符串内部表示的指针。



但是有几个要记住的事情:



- 由 c_str()返回的指针被导致写入的任何操作无效字符串

- 不要通过指针写任何东西

- 不要缓存指针



最后一件事:只使用 c_str()与C编写的库兼容。对于其他一切使用 std :: string 除非你真的知道你在做什么(虽然在那种情况下你不会问这个问题!)


引用:

//这会造成内存泄漏吗?



不行,但目的是什么线?


Will the following piece of code cause memory leak?

#include <iostream>

using namespace std;

void someFunction(const char* str)
{
	cout << "buffer   :" << str << endl;
	
	std::string abc(str);
	abc = abc.substr(5);
	
	cout <<"After manipulation    :" <<endl;

	str = abc.c_str(); //will this create memory leak?
}

int  main()
{
	std::string str = "My file is this one";
	
	const char* c = str.c_str();
	cout << c << endl;
	someFunction(c);
	return 0;
}

解决方案

It won't leak - in C++ 98 the c_str() buffer is cleaned up when the object is destroyed and in C++ 11 it's a pointer to the internal representation of the string.

However there's a couple of things to remember:

- pointers returned by c_str() are invalidated by any operation that causes a write to the string
- don't write anything through the pointer
- don't cache the pointer

And a final thing: Only use c_str() to be compatible with libraries written in C. For everything else use std::string unless you really know what you're doing (although in that case you wouldn't be asking this question!)


Quote:

//will this create memory leak?


Nope, but what's the purpose of that line?


这篇关于这段代码是否会导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆