问题描述
使用以下proto文件
message Foo {
// ...
}
message MyMessage {
Foo foo = 1;
}
我使用生成的 foo
方法设置了 set_allocated_foo
,该方法取得了指针的所有权:
MyMessage m;
m.set_allocated_foo(new Foo);
clang-tidy 会在 m
离开范围时给我以下警告:
warning: Potential memory leak [clang-analyzer-cplusplus.NewDeleteLeaks]
}
^
note: Memory is allocated
m.set_allocated_foo(new Foo);
^
有什么办法可以避免吗? (不使用 // NOLINT
)
解决方法
一种方法是使用 #ifdef __clang_analyzer__
:
MyMessage m;
auto* f = new Foo;
m.set_allocated_foo(f);
#ifdef __clang_analyzer__
delete f
#endif
我不知道这是不是最好的方法。