Why RAII rocks
bromeon.ch
bromeon.ch
int unsafe2()
{
A* a = new A;
int retval = 0;
if (a->f())
{
B* b = new B;
if (b->f())
retval = b->g();
else
retval = a->g();
delete b;
}
delete a;
return retval;
}
I agree that RAII is a good thing, but can we please avoid straw-man examples?Bjarne says, "Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient."
I'm not saying this is the best way to write this code - there are several reasons RAII is better. But in this case, "look how messy non-RAII code is!" isn't the reason.
KeytarHero could have wrote: "Here's a much shorter more realistic version of new/delete code that will have problems such as leakage after exceptions"
Since he didn't make that explicit, 3 replies seem to have misinterpreted the post as: "Here's a much shorter version that won't leak and doesn't need RAII"
Basically, his example is supposed to be "wrong" but it's a shorter version of "wrong".
RAII is something I do miss, though, even after years of C# I still feel lifetime management of objects is awkward.
Memory management is by and far the vast majority of resource management in C++ for me, which C# takes care of with garbage collection - so I don't miss RAII too much in C#. But if you tried to give me a C++ with using blocks but no RAII (read: you gave me C) I'd scream.
RAII is no panacea[1] - I'd say C#'s manual resource burden without RAII is still less than C++'s with RAII. Which is why I don't miss it too much. But it'd still be a nice addition. And I missed it dearly during my initial adoption of C#.
[1] e.g. in C++, you still have to worry about reference cycles, implementing the RAII constructs in the first place if existing ones aren't suitable, ensuring parents are kept in scope while referencing children, etc..
If you don't care about MSVC, IMHO new C code should be using the gcc cleanup extension: http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initial...
Even ignoring personal taste: I care about MSVC. I also care about clang. GCC is the one compiler I'm able to not care about.
> IMHO new C code should be using the gcc cleanup extension
Even if I didn't care about MSVC, I'd disagree.
I'm OK with extensions that are "harmless" in that the program will still run without them working if I #if them out on other compilers - error pragmas, deprecation annotations, static analysis hints, pre-C++11 override keywords, etc.
I'm not OK with self inflicting vendor lock-in for something as important as cleanup rely on a specific compiler's extensions - especially not when we have a perfectly standard, portable, significantly better tested (and thus less likely to have bugs) reasonable alternative in the form of C++ destructors.
If I'm not using C++ destructors, it's either because:
1) I'm doing small changes to an existing C project (in which case I'd be stylistically inconsistent with it's preferred cleanup patterns for minimal gain, since it almost certainly doesn't use the gcc cleanup extension)
or
2) because I can't rely on having decent C++ compilers on my target platforms (which means I can't rely on having GCC either, and thus can't rely on the gcc cleanup extension by definition.)
How recently? I've been enough versions back that clang documented pragmas haven't been available. The cleanup attribute... I can only find docs for GCC. Although I see LLVM bugs for it, so you're right about clang supporting it - at least on HEAD.
> gcc compiler extensions are otherwise still rather portable.
Portable or not, I'd say only about half the extensions I've sought out on clang have actually been available. If that.
> To clang and icc at least.
I should note in scenario #2 above I don't have these available either, since these are decent C++ compilers.
The file systems of Unix machines all have the same general structure. On your flimsy operating systems, you can create directories (folders) and give them names like Frodo or My Stuff and put them pretty much anywhere you like. But under Unix the highest level--the root--of the filesystem is always designated with the single character "/" and it always contains the same set of top-level directories:
/usr /etc /var /bin /proc /boot /home /root /sbin /dev /lib /tmp
and each of these directories typically has its own distinct structure of subdirectories. Note the obsessive use of abbreviations and avoidance of capital letters; this is a system invented by people to whom repetitive stress disorder is what black lung is to miners. Long names get worn down to three-letter nubbins, like stones smoothed by a river.
Except when they don't ;)
I've been using C++ for the past year at work. It's an absolute nightmare to learn.
Anyway it does prove your point: have been using c++ way longer than you and these don't immediately ring a bell. Always more to learn! (or at least, always more super subtle details you'll only encounter once in a lifetime)
I prefer working in python to C++, I just wish I had a lot more control over things like this. And no, __del__ isn't a good solution as that opens a whole can of worms (for one, it's not guaranteed to ever be called).
a(b(c()))
because just returning an object, then dropping the reference at the end of 'a' would do just that. You could also write your own context manager to wrap up a parameter. class Shadow(object):
def __init__(self):
self.value = None
def __enter__(self):
return self
def set(self, v):
self.value = v
def __exit__(self, *args):
if self.value is not None:
self.value.cleanup()
with Newdb() as db, Shadow() as d:
a(b(c(db, d))) with a(b(c)) as f:
but then you risk any of those functions throwing an exception and screwing up the whole thing. You can move the resource allocation from __init__ to __enter__, but now you split your initialization code over 2 constructors. You can just hope and pray that a and b don't throw an exception, but someone is gonna accidentally break that assumption. And even if they don't, you've now spent more time worrying about that then if you just did manual memory allocation.Or, in C++ you write
class Foo {
public:
Foo() {/*get handle*/}
~Foo() {/*release resource*/}
};
and you never have to worry again.After giving it some thought, I've come up with a better example which more closely maps to C++ RAII constructs, which shows that you don't need to split anything. Consider:
class Shadow(object):
def __init__(self):
# Initialization code
@classmethod
def __enter__(cls, *args, **kwargs):
return cls(*args, **kwargs)
def __exit__(self, *args, **kwargs):
# De-initialize
`__enter__` becomes three lines of boilerplate, which you could abstract out into an inheritable class, should you so desire.As for "In C++ you write", it's the same as saying "in Python you write __enter__ and __exit__", but instead of instantiating via `std::unique_ptr` you use `with`.
with alloc_resource() as resource:
resource.use()You complain about having to put initialization into 2 constructors, but there's the flip-side with things like mutexes. In c++, you have to have 2 classes, one for the lock and one for the guard. Whereas with a context-manager, you have one class and the locking code is in the __enter__ and __exit__.
with self.lock:
self.do_stuff()
In that case, I would say that the context-manager is nicer.I haven't done much with mutexes, but doesn't having it split over 2 classes introduce a race condition? Seems like a weird way to implement it to me.
{
Type obj;
// do stuff
}
// obj destructor just ran
C# and other languages have similar paradigms, but they require more attention to detail than a destructor does.What its really saying is if the lifetime is automatic or manual.
Maybe I'm confusing C with C++ or just outright confused, but to my understanding, nothing says that:
int foo[] = <massive amount of data>;
actually has to live on the stack.This might be possible in theory but I've never seen it in practice.
For instance,
std::unique_ptr<X> f () {
return std::make_unique<X>();
}
void h (std::unique_ptr<X> x) {
x->doSomething();
// x is released after this function returns
}
void g () {
auto x = f();
h(std::move(x));
}In ARC, all strong pointers may have multiple owners. In C++11 RAII, the typical, defining use is for single owners (std::unique_ptr) but multiple owners are supported too (std::shared_ptr).
In ARC, local pointers may be reclaimed before their scope ends, if the compiler determines no further use of the pointer. In C++11 RAII, all such resources are reclaimed only at scope end.
ARC is not exception-safe by default, you have to compile with -fobjc-arc-exceptions to make it exception safe; however Apple standards have been moving away from using exceptions for recoverable conditions for some time now. C++11 RAII is of course exception-safe by default, it's one of the rationales behind the technique.
Old, complicated and legacy does not equal bad.
We should strive for advancement and progress in our field. There is a large difference between this and chasing the latest fad JS framework.
Unless you are saying that programming is a solved problem and C++ is about as advanced as we'll ever get.
There's still a lot of need for tooling, testing, and letting people with smaller projects (and/or non-Mozilla use cases) shake out the bugs.
Give it a few successful years post 1.0, and Rust will be in a better place to truly take the mantle from C++.
That doesn't seem like a very high standard to hold Rust to. The problem is there's still holes we don't know about, and the developers who evangelize it are all starry-eyed about "never having to deal with memory again!"
When the shine wears off a bit (on both the language and its users), the big holes can be found and patched, the bilge pumps dispatched for the small ones, and Rust can move forward with a lot more confidence.