Shared_ptr; t(new char[num]) 意味着内存泄漏?
shared_ptr<void> t(new char[num])
意味着内存泄漏?
如果是这样,在这种情况下正确的做法是什么?
我应该使用shared_array<>反而?
我正在手动编辑“t”指向的字节,以便稍后在 TCP 流中传输。
shared_ptr<void> t(new char[num])
means memory leak?
If so, what is the correct practice in this case.
should I use shared_array<> instead?
I'm editing the bytes pointed by 't' manually for later transfer in a TCP Stream.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,这意味着未定义的行为。 (这可能有任何症状,包括内存泄漏。)对
delete
的调用必须与对new
的调用相匹配。你的没有。您可以使用new[]
进行分配,但可以使用delete
进行销毁。有两个简单的选择。您可以使用
shared_array
:或者,您可以使用
shared_ptr
到std::vector
:EDIT: Thanks to @Dennis Zickefoose for gently pointing out an error in my thinking. Parts of my answer are rewritten.
No, it means undefined behavior. (Which could have any symptom, including memory leak.) The call to
delete
must match the call tonew
. Yours doesn't. You allocate withnew[]
but destroy withdelete
.There are two easy choices. You can use
shared_array
:Or, you could use a
shared_ptr
to astd::vector
:EDIT: Thanks to @Dennis Zickefoose for gently pointing out an error in my thinking. Parts of my answer are rewritten.
正如我所见,您在 Q 中提到的
void
是一个拼写错误,因为在void *
上调用删除是标准保证的未定义行为。对于另一种数据类型,
您必须向
shared_ptr
提供自定义deletor
,以便可以调用delete []
。例如:
例如:
并调用为:
编辑:
既然您澄清在注释中使用的是 Boost 而不是 TR1(据我所知 TR1 没有共享数组),
您可以使用
shared_array
:As I see the
void
You mention in the Q is a typo, Since Calling delete on avoid *
is guaranteed Undefined Behavior by the Standard.For another data type,
You will have to provide your custom
deletor
to theshared_ptr
so you can calldelete []
.Eg:
For example:
And invoke as:
EDIT:
Since you clarified are using Boost in comments and not TR1(AFAIK TR1 doesn't have shared_array)
You can use
shared_array
:我想我明白你的来源 - 你需要
void *
指针,以便稍后可以将其转换为要序列化的最终类型。但正如其他人指出的那样,您无法删除void*
指针,shared_ptr
的代码也不能删除。由于您要分配一个 char 数组,因此这应该是您使用的智能指针的类型:
将原始 char 指针转换为另一种类型不应该比转换
void*
更成问题指针。I think I see where you're coming from - you want
void *
pointers so you can later cast it to the final type you're serializing. But as others have pointed out, you can't delete avoid*
pointer, and neither can the code forshared_ptr
.Since you're allocating an array of char, that should be the type of smart pointer you use:
Casting the raw char pointer to another type shouldn't be any more of a problem than casting a
void*
pointer.您正在对
void*
调用delete
,这是未定义的行为。然后使用结构或联合。
You're calling
delete
onvoid*
which is undefined behavior.Use a struct or union then.
我不知道C++11是否有shared_array, 但是Boost 可以——你应该使用它。
I don't know if C++11 has a shared_array, but Boost does — you should use that instead.