0
MyContainer a = ...;
a.myDeallocate();
a[0] = 3;       // This will crash

Given a C++ code snippet that looks like the above one, I would like to make the C++ compiler (either g++ or clang++) raise a warning saying that a must not be used after its deallocation, possibly by inserting a custom code:

MyContainer a = ...;
a.myDeallocate();
__should_not_use__(a); // If I put this code
a[0] = 3;              // The compiler will raise a warning at this point, hopefully.

Is there a way to do this?

aqjune
  • 478
  • 1
  • 3
  • 17

3 Answers3

1

You should get back to the principles and use RAII properly:

  1. The aquired resource is memory.
  2. Put the allocation in constructor.
  3. Put the deallocation in destructor:
MyContainer::~MyContainer(){
    deallocate();
};
  1. Adopt the rule of 0/3/5.
  2. Manage the lifetime with proper scoping:
{   MyContainer a {/*...*/};
    /* Use 'a' */
};  // 'a' is out of scope now.
Red.Wave
  • 2,790
  • 11
  • 17
0

I don't think this is possible at compile-time, since the deallocation may be conditioned on some user input not known at compile-time.

Assuming you have implemented operator[] for random access to elements in your container, a common practice is to use assert:

#include <cassert>

class MyContainer {
    // ...
    Type operator[](int i) {
        assert (0 <= i && i < this->size());
        // ...
    }
};

Of course, you need to maintain the size of the container for this to work.

If out-of-bound indexing happens, this raises an AssertionError at runtime, but not at compile-time.

ihdv
  • 1,927
  • 2
  • 13
  • 29
0

I don't think there is a way to generate a warning or error for this sort of thing at compile-time; the best you could do is a run-time check (and then throw an exception or abort() the program if myDeallocate() had previously been called)

If possible, the preferred approach is to do the myDeallocate() code only in MyContainer's destructor. Then your code can look like this:

{
   MyContainer a = ...;
}  // deallocation happens implicitly here

a[0] = 3; // causes compile-time error; run-time bug avoided
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234