Using memset on structures in C++

杀马特。学长 韩版系。学妹 提交于 2019-12-07 01:58:40

问题


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.

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++.

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) );

回答1:


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.

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

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




回答2:


Can you? Yes, probably. Should you? No.

While it will probably work, you're losing the state that the constructor has built for you. Adding to this, what happens when you decide to implement a subclass of this struct? Then you lose the advantage of reuseable code that C++ OOP offers.

What you ought to do instead is create a constructor that initializes the members for you. This way, when you sublass this struct later on down the line, you just use this constructor to aid you in constructing the subclasses. This is free, safe code! use it!

Edit: The caveat to this is that if you have a huge code base already, don't change it until you start subclassing the structs. It works as it is now.




回答3:


Yes, that would work. However, I don't think malloc is necessarily bad practice, and I wouldn't change it just to change it. Of course, you should make sure you always match the allocation mechanisms properly (new->delete, malloc->free, etc.).

You could also add a constructor to the struct and use that to initialize the fields.




回答4:


You could new foo (as is the standard way in C++) and implement a constructor which initialises foo rather than using memset.

E.g.

struct Something
{
    Something()
        : m_nInt( 5 )
    {

    }

    int m_nInt;
};

Also don't forget if you use new to call delete when you are finished with the object otherwise you will end up with memory leaks.



来源:https://stackoverflow.com/questions/2773927/using-memset-on-structures-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!