Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use smart pointer in this situation

I want to use smart pointer in the following situation:

   SOME_STRUCT* ptr = new SOME_STRUCT;
   ptr->SOME_MEMBER = new BYTE[100];
   CallSomeAPI(ptr);

now the API can either return error or pass successfully but in both those cases i want to delete the object , one way can be to write delete statement during error exit and during normal exit.

But how can i use a smart pointer for these pointers ? By smart pointers i mean unique_ptr, shared_ptr , etc. whichever can work !

Thanks!

like image 789
stng Avatar asked May 15 '15 08:05

stng


People also ask

What is the use of smart pointers?

In modern C++ programming, the Standard Library includes smart pointers, which are used to help ensure that programs are free of memory and resource leaks and are exception-safe.

What is a smart pointer and when should I use one?

A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way. Smart pointers should be preferred over raw pointers.

What is a smart pointer why it is used and describe the types?

A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.

How are smart pointers implemented?

In C++, a smart pointer is implemented as a template class that mimics, by means of operator overloading, the behaviors of a traditional (raw) pointer, (e.g. dereferencing, assignment) while providing additional memory management features.


1 Answers

You can write a custom deleter for unique_ptr.

struct my_deleter {
    void operator()(SOME_STURCT* ptr) const {
        delete[] ptr->SOME_MEMBER;
        delete ptr;
    }
};

using my_ptr = std::unique_ptr<SOME_STRUCT, my_deleter>;

and I would suggest changing new SOME_STRUCT; to new SOME_STRUCT{}; to default initialize SOME_MEMBER to nullptr.

I am not 100% happy with this solution, so perhaps look into scope_guard or writing a wrapper class for your struct.

like image 79
Pubby Avatar answered Sep 25 '22 04:09

Pubby