Skip to content

Parameter handling helpers

Raymond Chen edited this page Jul 23, 2019 · 1 revision

The parameter handling helpers assist in managing output parameters to ABI functions.

Usage

The parameter handling helpers are defined in wil/common.h.

#include <wil/common.h>

assign_to_opt_param and assign_null_to_opt_param

template<typename T> void assign_to_opt_param(T* outParam, T value);
template<typename T> void assign_null_to_opt_param(T* outParam);

Some functions return additional information through pointer parameters. The caller can pass nullptr to indicate that they do not want the additional information. In that sense, the parameters are considered "optional".

The assign_to_opt_param function sets the value of an optional parameter to the specified value.

The assign_null_to_opt_param function sets the value of an optional parameter to nullptr.

If the optional parameter is missing (nullptr), then nothing happens.

Note: If you call assign_to_opt_param, and the outParam is nullptr, then the value is discarded. Do not use assign_to_opt_param if the value requires special resource management.

Examples

HRESULT CreateWidget(
    _Out_ Widget** widget,
    _Out_opt_ PCWSTR* name = nullptr,
    _Out_opt_ bool* isRemote = nullptr)
{
    // Preinitialize output parameters in case of error.
    wil::assign_null_to_opt_param(name);
    wil::assign_to_opt_param(isRemote, false);
    *widget = nullptr;

    wil::unique_cotaskmem_string widgetName;
    RETURN_IF_FAILED(GenerateUniqueName(&widgetName));


    auto createdWidget = wil::unique_widget(new(std::nothrow) Widget(widgetName.get()));
    RETURN_IF_NULL_ALLOC(createdWidget);

    // WRONG! Will leak the string if name is nullptr.
    wil::assign_to_opt_param(name, widgetName.release());

    // RIGHT: Transfer from smart pointer only if there is a consumer.
    if (name)
    {
        *name = widgetName.release();
    }

    wil::assign_to_opt_param(is_remote, widget->is_remote);
    *widgetResult = widget.release();
    return S_OK;
}