std :: string :: c_str()如何返回不会导致内存泄漏或未定义的c字符串内容的c字符串? [英] How does std::string::c_str() return a c-string that does not cause a memory leak or undefined c-string contents?
问题描述
我正在写一个类似于std :: string的字符串类作为家庭作业,但我不知道如何返回一个不会导致内存泄漏的c字符串,并保证保持不变直到它不再使用。我目前有:
I'm writing a string class that is similar to std::string for a homework assignment, but I cannot figure out how to return a c-string that does not cause a memory leak and is guaranteed to stay the same until it is no longer in use. I currently have:
const char* string::c_str()
{
char c[_size+1];
strncpy(c,_data,_size);
c[_size]='\0';
return c;
}
但内容在调用后不久就会覆盖。如果我做动态分配,我将有一个内存泄漏或任何时候只有一个c字符串可以存在从给定的字符串。如何避免这种情况?
but the contents are overridden shortly after it is called. If I do dynamic allocation, I'll have either a memory leak or only one c-string can exist from a given string at any time. How can I avoid this?
推荐答案
但是 c_str指向的字符串
只有在下一次修改(或销毁) std :: string
之前才有明确定义。
But the string pointed to by c_str
is only well-defined until the std::string
is next modified (or destroyed).
实现这可能是简单地返回一个指针到你的内部缓冲区(假设它是null终止)。请记住,符合标准的 c_str
必须在O(1)次操作;因此不允许复制。
One way to achieve this might be simply to return a pointer to your internal buffer (assuming it's null-terminated). Bear in mind that a standards-compliant c_str
has to operate in O(1) time; so copying is not permitted.
这篇关于std :: string :: c_str()如何返回不会导致内存泄漏或未定义的c字符串内容的c字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!