Catriel
Catriel

Reputation: 647

What is the cleanest way of defining a no-delete pointer?

I recently came across an old C-function returning a pointer to an static array. I wrote a wrapper around that function and returned a std::unique_ptr that uses a no-delete to emphasize the type of pointer being returned - a "don't delete me" warning to the user. Here is a sample code

 extern "C" int *f(int i);

 struct noop
 {
      template <typename T>
      void operator() (T t) const noexcept
      {
      }
 };
 class MyClass
 {
     public:          
     std::unique_ptr<int, noop> F(int value) const 
      { 
            return std::unique_ptr<int, noop>(f(value));
      }
 };

Is there a cleaner way of doing this without defining a no-delete struct?

Upvotes: 4

Views: 1424

Answers (2)

einpoklum
einpoklum

Reputation: 131996

The C++ coding guidelines suggest using aliases or "dummy" wrappers to indicate ownership, or non-nullness:

For their implementation, have a look at:

https://github.com/Microsoft/GSL/blob/master/include/gsl/pointers

You'll see the example of owner<> and of non_null<>.

You could similart definition. Clearly, a non-owning pointer must not be deleted; if you just want a reminder, then

template <class T, class = std::enable_if_t<std::is_pointer<T>::value>>
using non_owner = T;

and if you want enforcement, copy and adapt the code for non_null<> from the link.

Upvotes: 0

Daniel Jour
Daniel Jour

Reputation: 16156

[..] an old C-function returning a pointer to an static array. I wrote a wrapper around that function and returned a std::unique_ptr

Don't. Returning std::unique_ptr says to the caller:

  • you own this memory, clean up after yourself
  • you own this memory, nobody else will interfere (thread safety)
  • you own this memory. Thus you get a new object every time you call (the wrapper function).

None of this is true for a pointer to a static array!

Stick with the raw pointer or use some wrapper class to allow reference-like access. std::reference_wrapper to also provide semantics like the raw pointer when copying for example.

Upvotes: 6

Related Questions