在C ++中的结构上使用memset [英] Using memset on structures in C++

查看:173
本文介绍了在C ++中的结构上使用memset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.我正在为自己的工作修复旧代码.它目前是用C ++编写的.他们将静态分配转换为动态分配,但未编辑memsets/memcmp/memcpy.这是我第一次编程实习,所以对我的新手式问题不屑一顾.

Hey guys. I am working on fixing older code for my job. It is currently written in C++. They converted static allocation to dynamic but didn't edit the memsets/memcmp/memcpy. This is my first programming internship so bare with my newbe-like question.

以下代码在C中,但是我想在C ++中使用(我读到malloc在C ++中不是一种好习惯).我有两种情况:首先,我们创建了f.然后,您可以使用& f来填充零.第二个是指针* pf.我不确定如何将pf设置为全0,就像C ++中的上一个示例一样.

The following code is in C, but I want to have it in C++ ( I read that malloc isn't good practice in C++). I have two scenarios: First, we have f created. Then you use &f in order to fill with zero. The second is a pointer *pf. I'm not sure how to set pf to all 0's like the previous example in C++.

您可以只执行pf = new foo而不是malloc然后调用memset(pf, 0, sizeof(foo))吗?

Could you just do pf = new foo instead of malloc and then call memset(pf, 0, sizeof(foo))?

struct foo { ... } f;
memset( &f, 0, sizeof(f) );

//or

struct foo { ... } *pf;
pf = (struct foo*) malloc( sizeof(*pf) );
memset( pf, 0, sizeof(*pf) );

推荐答案

是的,但前提是foo是POD.如果它具有虚拟函数或远程C ++ ish以外的任何其他功能,请不要在其上使用memset,因为它会遍历struct/class的内部.

Yes, but only if foo is a POD. If it's got virtual functions or anything else remotely C++ish, don't use memset on it since it'll stomp all over the internals of the struct/class.

您可能想代替memset做的是给foo一个构造函数,以显式初始化其成员.

What you probably want to do instead of memset is give foo a constructor to explicitly initialise its members.

如果要使用new,请不要忘记相应的删除.更好的方法是使用shared_ptr:)

If you want to use new, don't forget the corresponding delete. Even better would be to use shared_ptr :)

这篇关于在C ++中的结构上使用memset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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