aqjune
aqjune

Reputation: 552

How to warn not to use a variable after some point in g++/clang++?

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?

Upvotes: 0

Views: 67

Answers (3)

ihdv
ihdv

Reputation: 2287

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.

Upvotes: 0

Red.Wave
Red.Wave

Reputation: 4251

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.

Upvotes: 1

Jeremy Friesner
Jeremy Friesner

Reputation: 73161

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

Upvotes: 0

Related Questions