Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

owner<T*> p syntax in cpp core guidelines

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 ?

like image 445
arenard Avatar asked Jul 13 '17 07:07

arenard


2 Answers

There is a note about the semantics of owner further down the page:

Note owner<T*> has no default semantics beyond T*. 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 an owner<T*> is a member of a class, that class better have a destructor that deletes 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.

like image 197
Rakete1111 Avatar answered Nov 12 '22 22:11

Rakete1111


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

like image 1
Sorush Avatar answered Nov 12 '22 21:11

Sorush