简体   繁体   English

C++。 铸型 arrays 需要 memory 管理吗?

[英]C++. Do type casted arrays need to be memory managed?

The code looks like this:代码如下所示:

std::string str = (char *) xmlTextReaderReadString(*xml);

Memory management for str works fine. str 的 Memory 管理工作正常。 str makes a deep copy of the character array. str 对字符数组进行深拷贝。

What is being made when typecasting is what I am worried about.我担心的是类型转换时所做的事情。 xmlTextReaderReadString is returning a typedefed unsigned char * or how they defined it an (xmlChar*). xmlTextReaderReadString 正在返回一个 typedefed unsigned char * 或他们如何定义它 (xmlChar*)。

I couldn't find a viable question on stack overflow, but if you did, just link it and I'll delete this post.我找不到关于堆栈溢出的可行问题,但如果你找到了,只需链接它,我会删除这篇文章。

So forth with an example like this:以这样的例子为例:

xmlTextReaderGetAttribute (*xml, (xmlChar*)"type"))

Do I need to memory manage the typecasted "type"我是否需要 memory 管理类型转换的“类型”

Yes, you need to call xmlFree() on the returned value from xmlTextReaderReadString , after building your std::string .是的,在构建std::string之后,您需要对xmlTextReaderReadString的返回值调用xmlFree()

I never used that library, but a google search turned up the answer in seconds.我从来没有使用过那个库,但是谷歌搜索在几秒钟内就找到了答案。

It also has nothing to do with the cast.这也与演员阵容无关。 You got a value, you can use it, but you need to free it afterward.你有一个值,你可以使用它,但你需要在之后释放它。 If you use the value, in the meantime to build a std::string , the std::string will manage its own copy, you still need to manage yours.如果您使用该值,同时构建std::stringstd::string将管理自己的副本,您仍然需要管理自己的副本。

The second API you use is also labelled您使用的第二个 API 也标有

The string must be deallocated by the caller字符串必须由调用者释放

but that applies to the returned value, not to "type" .但这适用于返回值,而不适用于"type" This one is a literal that should not be freed.这是一个不应该被释放的文字。

http://www.mit.edu/afs.new/sipb/user/yoz/libxml2-2.7.3/doc/html/libxml-xmlreader.html http://www.mit.edu/afs.new/sipb/user/yoz/libxml2-2.7.3/doc/html/libxml-xmlreader.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM