8

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 ?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
arenard
  • 652
  • 6
  • 12
  • 2
    `p` is an instance of the class `owner` which is a template and accept the parameter `T*`? is that what you are asking? – Adrian Maire Jul 13 '17 at 07:32
  • is it linked to [this one](https://stackoverflow.com/questions/38449366/what-is-templateclass-t-using-owner-t)? – sop Jul 13 '17 at 08:13
  • yes! now I really understand where it comes from! this is declared in the microsoft library as an empty template – arenard Jul 13 '17 at 08:23

2 Answers2

10

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.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
1

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

Sorush
  • 3,275
  • 4
  • 28
  • 42
  • 2
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Oct 10 '20 at 13:54