3

I am learning windows programming with the help of MSDN.Why would somebody initialize an object like the following?

WNDCLASS wc = { };

Will this zero all the memory of the object? Whole source code is following:

#ifndef UNICODE
#define UNICODE
#endif 

#include <windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    // Register the window class.
    const wchar_t CLASS_NAME[]  = L"Sample Window Class";
    WNDCLASS wc = { };

    wc.lpfnWndProc   = WindowProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    // Create the window.

    HWND hwnd = CreateWindowEx(
        0,                              // Optional window styles.
        CLASS_NAME,                     // Window class
        L"Learn to Program Windows",    // Window text
        WS_OVERLAPPEDWINDOW,            // Window style

        // Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL,       // Parent window    
        NULL,       // Menu
        hInstance,  // Instance handle
        NULL        // Additional application data
        );

    if (hwnd == NULL)
    {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    // Run the message loop.

    MSG msg = { };
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hwnd, &ps);

            FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));

            EndPaint(hwnd, &ps);
        }
        return 0;

    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
4

1 回答 1

2

大概是为了利用自动初始化。

参考:

C++03 标准 8.5.1 聚合
第 7 段:

如果列表中的初始化器少于聚合中的成员,则每个未显式初始化的成员都应进行值初始化(8.5)。[例子:

 struct S { int a; char* b; int c; };
 S ss = { 1, "asdf" };

ss.a使用、 和形式的表达式的值进行初始化1,即. ]ss.b"asdf"ss.cint()0

虽然值初始化在
C++03 8.5 Initializers
Para 5 中定义:

对T 类型的对象进行值初始化意味着:
— 如果 T 是具有用户声明的构造函数(12.1)的类类型(第 9 条),则调用 T 的默认构造函数(如果 T没有可访问的默认构造函数);
— 如果 T 是没有用户声明的构造函数的非联合类类型,则 T 的每个非静态数据成员和基类组件都是值初始化的;
— 如果 T 是一个数组类型,那么每个元素都是值初始化的;
— 否则,对象被零初始化

于 2012-09-25T09:38:42.040 回答