Re: private construction on GCC
brianhray@gmail.com wrote:
I get an access exception on Release() on GCC but worked on different
compiler,
Ok, sounds like undefined behavior.
I am trying to figure out if there is anything with this code
in a header:
class CountObject {
private:
long count;
public:
CountObject() : count(0) {}
CountObject(const CountObject&) : count(0) {}
virtual ~CountObject() {}
CountObject& operator=(const CountObject &) { return *this; }
void Grab() { count++; }
void Release() {
if (count > 0) count--; //< Exception Here
if (count <= 0) {
delete this;
}
}
// attribute functions
long Count() const { return count; }
};
Any insight would be helpful. What is the best way (most standard) to
prevent this problem.
The code you posted, does not show any problems. However, calling
delete this;
can be tricky. If I was to take a wild guess, I would conjecture that in
your other code, you call Release() (or some other member function) on an
object that has already self-detonated. In that case, you enter UB.
Another catch with "delete this" is that is presupposes the object has been
created via new(). Maybe you call Release() on an object on the stack
causing UB that way.
Please, post a minimal complete program that reproduces the problem. Then,
we can set the guess work asside and get to the heart of the matter.
Best
Kai-Uwe Bux