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