Re:Bjarne Stroustrup – The Essence of C++ [video]
by harrytuttle on Tuesday September 17, 2013 @06:42AM
(#6398533)
What 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;
// ...
}
Re:Bjarne Stroustrup – The Essence of C++ [video]
by skrebbel on Tuesday September 17, 2013 @07:18AM
(#6398619)
Gadget 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++.
Re:Bjarne Stroustrup – The Essence of C++ [video]
by kybernetyk on Tuesday September 17, 2013 @06:47AM
(#6398549)
you 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).
Re:Bjarne Stroustrup – The Essence of C++ [video]
by fhd2 on Tuesday September 17, 2013 @07:24AM
(#6398637)
Well, 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 :(
There are two better options:
Or, if it really has to be a pointer: Both will be automatically freed as soon as the scope is exited.