C26160

warning C26160: Il chiamante probabilmente non riesce ad utilizzare il blocco <lock> prima di chiamare la funzione <func>.

L'avviso C26160 è simile all'avviso C26110 eccetto che il livello di fiducia è inferiore.Ad esempio, la funzione può contenere errori di annotazione.

Esempio

Il codice seguente genera l'avviso c26160.

struct Account
{
    _Guarded_by_(cs) int balance;
    CRITICAL_SECTION cs;

    _No_competing_thread_ void Init() 
    {
        balance = 0; // OK
    }

    _Requires_lock_held_(this->cs) void FuncNeedsLock();

    _No_competing_thread_ void FuncInitCallOk()
        // this annotation requires this function is called 
        // single-threaded, therefore we don't need to worry 
        // about the lock
    {
        FuncNeedsLock(); // OK, single threaded
    } 

    void FuncInitCallBad() // No annotation provided, analyzer generates warning
    {
        FuncNeedsLock(); // Warning C26160
    }

};

Il codice seguente mostra una soluzione all'esempio precedente.

struct Account
{
    _Guarded_by_(cs) int balance;
    CRITICAL_SECTION cs;

    _No_competing_thread_ void Init()
    {
        balance = 0; // OK
    }

    _Requires_lock_held_(this->cs) void FuncNeedsLock();

    _No_competing_thread_ void FuncInitCallOk()
        // this annotation requires this function is called 
        // single-threaded, therefore we don't need to worry 
        // about the lock
    {
        FuncNeedsLock(); // OK, single threaded
    } 

    void FuncInitCallBadFixed() // this function now properly acquires (and releases) the lock
    {
        EnterCriticalSection(&this->cs); 
        FuncNeedsLock();  
        LeaveCriticalSection(&this->cs);
    }
};