When I use the following code, I get a warning (From applying cppcoreguideline). Code:
SampleClass *object = nullptr;
object = new SampleClass();
Warning:
warning: assigning newly created 'gsl::owner<>' to non-owner 'SampleClass *' [cppcoreguidelines-owning-memory]
When I searched and get to this link https://releases.llvm.org/8.0.1/tools/clang/tools/extra/docs/clang-tidy/checks/cppcoreguidelines-owning-memory.html
which I am not able to understand, Could someone kindly explain this in simple terms.
gsl::owner<T*>
is meant to designate that whoever holds this object is the owner of the underlying T
object and is responsible for freeing the memory later. Note that an explicit delete operation is still required — the GSL annotation is meant to assist static analysis tools. (For more on ownership, see this post.)
When you assign a gsl::owner to a raw pointer such as SampleClass *object
, the ownership semantics are lost and the static analyzer (clang-tidy in this case) is unable to verify that object
is used correctly in the future. That's why you get a warning in this case: because it's a bad idea to lose this information and will often lead to incorrect code.
To fix this error you can annotate objects manually by using gsl::owner explicitly, for instance gsl::owner<SampleClass*> object;
.
Another, possibly simpler alternative would be to use std::unique_ptr
(usually via std::make_unique<SampleClass>()
) which will provide strong safety guarantees at compile time (even without the use of another analyzer like clang-tidy) as long as it's used properly. It will also automatically delete the object, which gsl::owner does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With