sal

Is it appropriate to use _In_opt_ on a parameter passed by value if the type is a class implementing the explicit operator bool?


If the object passed by value would be "empty" (the explicit operator bool would return false), is it ok to consider that the parameter is optional? Caller could send empty or valid objects by value. Can we mark the parameter _In_opt_ ? I know it is against the MS SAL documentation which refers to pointers, but from logical point of view, in this situation, it would be optional to pass a valid object.

Example: bool Test(_In_opt_ Id id)

class Id
{
public:

    Id(_In_ uint32_t id = 0) : m_id(id) {}

    explicit operator bool() const
    {
        return m_id != 0;
    }

private:

    uint32_t m_id = 0;
};



bool Test(_In_opt_ Id id)
{
    if (!id)
    {
        return false;
    }

    // Do something with id

    return true;
}



int main()
{
    Id emptyId;
    Id someId(3);

    if (Test(emptyId))
    {
    }
}

Solution

  • The primary audience for SAL Annotations is static code analyzers. Their meaning has a robust definition. The _In_opt_ annotation is meaningful for pointers only: It describes a pointer to read-only data that can be a null pointer.

    While SAL annotations also serve as documentation for humans, they must still be used as intended. In the example provided, the _In_opt_ annotation cannot be used to convey "logical" optionality.

    If you want to document this property, you still have options:

    Doing all of the above is usually a good idea, in addition to using SAL annotations where appropriate.