Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 740
Catriel Avatar asked Sep 16 '25 18:09

Catriel


1 Answers

[..] 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.

like image 162
Daniel Jour Avatar answered Sep 18 '25 09:09

Daniel Jour