Search code examples
c++new-operatordequedelete-operator

New and delete operators without effect on the contents of a Deque of pointers to this class


I have a problem that I have been tackling since the last two days, but as a rather inexperienced programmer it is normal I assume. My question may have an easy solution, but I couldn't find a quick reference, so decided to ask it to others.

In one thread of an application, I create with new, a pointer to a user defined class. Immediately after it, I push that new created pointer into a deque of pointers to this user defined class, with push_back() method.

This deque under concern had been passed to this thread from the main function of the application, where the contents of this user-defined class are processed in the main loop. Thus, when a new pointer enters into the deque, it is taken in main thread, and used.

My problem is that I need to make sure that the memory allocated to the contents of this class should be deallocated after use, because they store very large image arrays. Otherwise, the program crashes. For this, I have used delete immediately after the push_back() call in the thread, assuming that the memory is eventually free, but is stored only in the deque. However, apparently, the contents of the address pointed by the pointer in deque is also deleted. This is not what I desire.

Is there a way to decouple both, maybe without introducing pointers? I think new and delete are only valid in pointers. More precisely, is there a way to pass the contents of this class to the deque and then delete it, without affecting what is in the deque?


Solution

  • Instead of using raw pointers, consider using Boost Pointer Container Library:

    Boost.Pointer Container provides containers for holding heap-allocated objects in an exception-safe manner and with minimal overhead. The aim of the library is in particular to make OO programming easier in C++ by establishing a standard set of classes, methods and designs for dealing with OO specific problems

    But this is a valid choice if:

    the stored objects are not shared, but owned exclusively, or
    
    the overhead implied by smart pointers is inappropriate
    

    Otherwise, if your image file pointers are shared, consider using std::shared_ptr as pointed out in the comments.

    If Boost Pointer Container fits your needs, you can use boost::ptr_deque