Call OH_NativeWindow_NativeObjectUnreference() in a timely manner after use to decrement the reference count correspondingly, which was incremented via OH_NativeWindow_NativeObjectReference() or OH_NativeWindow_GetLastFlushedBufferV2(). Otherwise, the objects cannot be reclaimed, causing memory leaks.
// rules.json
{
"rules": {
"cpp": {
"ResourceLeak": [
{
"ruleId": "NativeObjectReference API Not Paired",
"severity": "error",
"skip": false
}
]
}
}
} // Positive example
#include "native_window/external_window.h"
void IncreaseRefWithDecrease()
{
OHNativeWindow *window;
// Obtain an OHNativeWindow instance.
OH_NativeWindow_NativeObjectReference(window);
// Logic processing.
OH_NativeWindow_NativeObjectUnreference(window);
}
void BufferV2WithtDecrease(int *fenceFd, float matrix[16])
{
OHNativeWindow *window;
OHNativeWindowBuffer *buffer;
// Obtain an OHNativeWindow instance.
OH_NativeWindow_GetLastFlushedBufferV2(window, &buffer, fenceFd, matrix);
// Logic processing.
OH_NativeWindow_NativeObjectUnreference(buffer);
} // Negative example
#include "native_window/external_window.h"
void IncreaseRefWithoutDecrease()
{
OHNativeWindow *window;
// Obtain an OHNativeWindow instance.
// Increment the reference count.
OH_NativeWindow_NativeObjectReference(window);
// Use the window object.
// Not unreferenced; reference count not decremented accordingly - memory leak!
} For details about how to configure Code Scanner check rules, see Using codescanner.