Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Warning: Assigning newly created gsl::owner<> to non-owner

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.

like image 535
Ravi Avatar asked Jun 29 '20 22:06

Ravi


1 Answers

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.

like image 110
jtbandes Avatar answered Sep 25 '22 07:09

jtbandes