In cpp core guidelines: Example of non owning raw pointer I do not understand the following code:
template<typename T>
class X2 {
// ...
public:
owner<T*> p; // OK: p is owning
T* q; // OK: q is not owning
};
what is this syntax owner<T*> p
?
There is a note about the semantics of owner
further down the page:
Note
owner<T*>
has no default semantics beyondT*
. It can be used without changing any code using it and without affecting ABIs. It is simply a indicator to programmers and analysis tools. For example, if anowner<T*>
is a member of a class, that class better have a destructor thatdelete
s it.
It's basically the almost same as the proposed std::observer_ptr
. The difference is that owner
stores a pointer and "owns" it, although it doesn't do any RAII like std::unique_ptr
. It should be used when you want to be more explicit that a raw pointer is a owning pointer.
Note that the "syntax" here is just a variable of a template class, it's not a keyword or something.
As Rakete1111 mentioned, owner<T*>
is the same as T*. So we can have owner
as a type alias for T.
template<class T>
using owner = T;
Now we can have a convention for our code that pointers are defined by owner
when the class containing them is responsible for deleting them.
A simple example that owner acts as a raw pointer:
owner<int*> p = new int;
*p = 1;
std::cout<<*p; // 1
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