6 ms·
The point of the example is that this is how NOT to do it in C++. There are two better options: void f(int n, int x) { Gadget p(n); // Stack allocated
by fhd2 13y ago
The point of the example is that this is how NOT to do it in C++.
There are two better options:
void f(int n, int x) {
Gadget p(n); // Stack allocated
// ...
if (x < 100) throw new Exception("Weird!); // no leak
if (x < 200) return;
// ...
}
Or, if it really has to be a pointer:
void f(int n, int x) {
std::unique_ptr<Gadget> p = new Gadget(n); // Smart pointer
// ...
if (x < 100) throw new Exception("Weird!); // no leak
if (x < 200) return;
// ...
}
Both will be automatically freed as soon as the scope is exited.
- harrytuttle 13y agoWhat I was hoping you'd say :) This is fine until I want to do this, at which point C++ becomes a memory management bastard: void f(int n, int x) { Gadget g = new Gadget(n); // ... if (x < 100) throw new GadgetException("Gadget broke", x); if (x < 200) return; // ... }
- kybernetyk 13y agoyou can always fake a defer: void f(int n, int x) { Gadget g = new Gadget(n); std::shared_ptr<void> defer(nullptr, [g](void *) { delete g; }); ... But honestly ... I'd just use a stack allocated object - or a smart pointer. In the last year I didn't write one delete. (I'm a full time C++ dev).
- skrebbel 13y agoGadget g = new Gadget(n); That code won't compile unless Gadget has an assignment operator that accepts a pointer, which is, well, not a very common scenario. Note: I'm not trying to be nitpicky. I really don't understand what you mean when you write that you "want to do this". Now, I don't know anything about you, but based off your comments in this thread I'm not sure you have a working knowledge of C++.
- fhd2 13y agoWell, what's easy in Java here is that you're effectively always working with shared objects. That's easy to use, but in my experience quite error prone, I can't count how many memory leaks I fixed in Java/JS code. YMMV. In C++, you have various ways of referencing and passing objects, so you need to be aware of the lifetime and ownership of objects. It's arguably harder, and unfortunately, the C heritage makes it a lot harder than it needs to be :(
- easytiger 13y agoisn't that illegal?
- detrino 13y agoThis code makes no sense. I think you do not understand C++ very well.