Difference in functionality between ARC and RAII
Asked Answered
J

0

6

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, bars destructor would get called.
If obj was an object in a ARC language, bars 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)?

Jeu answered 5/7, 2016 at 15:6 Comment(4)
pretty much. With ARC enabled every pointer (objective-c) or object reference(swift) more or less models a std::shared_ptrHulky
Note that, for the above, it depends on the type of bar 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 write auto bar = obj();, omitting the new 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.Hashish
@Hashish I intended this to a language-agnostic example (as it isn't valid C++ anyway). I considered adding the language_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/RAIIJeu
Technically, ARC has nothing to do with initialization. If you write NSString *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 of NSObject, and is triggered through ARC by releasing an object.Andvari

© 2022 - 2024 — McMap. All rights reserved.