I'm trying to understand the difference between C++ like RAII and Obj-C or Swift like ARC.
Let's say I have this function:
foo() {
bar = new obj();
} // lifetime of bar object ends
If obj was an object in a RAII language, bar
s destructor would get called.
If obj was an object in a ARC language, bar
s retain count would be decreased by one, probably deallocating it.
So at this point, both of the approaches have some functionality that the other lacks:
ARC knows whether bar
is pointed to in some other part of the program (which is basically impossible in my example, but bear with me), and can use that information to its advantage.
RAII can do more than just deallocating the object, as you can define the destructor function just like you want.
However, C++ also has smart pointers and Swift and Obj-C has deallocation functions. So don't these languages basically have the same functionality, and Swift can basically be called a RAII language and C++ be called an ARC language (or let's say can be used can be used with an ARC idiom)?
std::shared_ptr
– Hulkybar
whether the destructor gets called. If it's a smart pointer, yes, if it's a naked pointer, no. A typical C++ programmer would just writeauto bar = obj();
, omitting thenew
and thus not forcing a heap allocation. In this latter case, destructor gets called. If it's a resource, you'll probably end up writing a move constructor so you can keep track of whether the resource should be free'd in destructor. – HashishC++
anyway). I considered adding thelanguage_agnostic
tag, but I thought this would be weird, as I talk about specific languages in my question. So consider this initialization as intialization of object with its lifetime managed by ARC/RAII – JeuNSString *a = [NSString alloc];
, ARC will still deal with retaining and releasing, but no initialization has been done. Objective-C has no concept of a constructor which is automatically called. On the flip-side, it also doesn't really have the concept of an automatic destructor. That's really a function ofNSObject
, and is triggered through ARC by releasing an object. – Andvari