将构造函数中的结构归零 [英] Zeroing out a struct in the constructor

查看:24
本文介绍了将构造函数中的结构归零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Win32 编程中使用了广泛的结构.很多时候只使用它们的一些字段,而所有其他字段都设置为零.例如:

A wide range of structures is used in Win32 programming. Many times only some of their fields are used and all the other fields are set to zero. For example:

STARTUPINFO startupInfo; // has more than 10 member variables
ZeroMemory( &startupInfo, sizeof( startupInfo ) ); //zero out
startupInfo.cb = sizeof( startupInfo ); //setting size is required according to MSDN
startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK;
//Now call CreateProcess() passing the startupInfo into it

我想停止复制粘贴此类代码,而是使用一种关心归零和设置参数的抽象.让我们假设我只需要像示例中那样初始化结构体,不需要其他调整.以下是一个好的解决方案吗?可能存在哪些问题?

I want to stop copy-pasting such code and instead use an abstraction that would care about zeroing and setting parameters. Let's presume I only need the struct initialized as in example, and no other tuning is ever needed. Is the following a good solution? What are possible problems?

class CStartupInfo : public STARTUPINFO {
public:
   CStartupInfo()
   {
       ZeroMemory( this, sizeof( STARTUPINFO ) );
       cb = sizeof( STARTUPINFO );
       dwFlags = STARTF_FORCEOFFFEEDBACK;
   }
};

我特别关注 ZeroMemory() 调用 - 看起来我完全控制了代码并且该类没有 vtable 并且以这种方式调用 ZeroMemory() 是安全的并且两个代码片段之间没有太大区别,除了后者提供了一个抽象.有什么注意事项吗?

I'm in particular concerned about the ZeroMemory() call - looks like I fully control the code and the class has no vtable and calling ZeroMemory() this way is safe and there's no big difference between the two code snippets except that the latter provides an abstraction. Are there any caveats?

推荐答案

我认为这是使此类结构更加防弹的好方法.我不确定为什么其他人似乎不喜欢这种技术.我偶尔会使用它,但不会像平时那样经常使用,因为出于某种原因,同事似乎不太喜欢它.

I think this is a fine way to make such structures more bulletproof. I'm not sure why others seem to not like the technique. I use it occasionally, but not as often as I otherwise might because it doesn't seem to be very well liked by coworkers for some reason.

我不经常在已发表的材料中看到它——我现在在快速谷歌中唯一能找到的是 Paul DiLascia 于 1997 年 8 月在 MSJ 上发表的一篇文章(http://www.microsoft.com/MSJ/0897/C0897.aspx):

I don't see it used in published material very often - the only one I could find in a quick Google right now is an article by Paul DiLascia in MSJ August 1997 (http://www.microsoft.com/MSJ/0897/C0897.aspx):

CRebarInfoCRebarBandInfo 是 C 结构 REBARINFOREBARBANDINFO 的程序员友好的 C++ 版本,带有构造函数在适当地设置 cbSize 成员之前将对象初始化为零.

CRebarInfo and CRebarBandInfo are programmer-friendly C++ versions of the C structs REBARINFO and REBARBANDINFO, with constructors that initialize the objects to all zeroes before setting the cbSize member appropriately.

我想不出太多缺点(除了缺乏接受度).如果有人能指出更具体的内容,我将不胜感激.

I can't think of much in the way of drawbacks (except the lack of acceptance). If anyone else can point to something more concrete, I'd appreciate it.

这篇关于将构造函数中的结构归零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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