Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>But Objective-C objects still are more or less manually managed, and RAII idiom is entirely absent from the language.</p> </blockquote> <p>I think this would seem to answer your question anyhow. Because Objective-C objects are reference counted, they already fulfill the purpose smart pointers were created for: to divorce or tie the lifetime of an object from the scope of the method it's contained in. <code>scoped_ptr</code>s can be recreated with autorelease pools, and <code>shared_ptr</code>s with <code>-retain</code>-<code>-release</code> or <code>strong</code> references. </p> <p>But saying no is boring. If you really want to mingle Objective-C and C++ like this, we'll need to first loosen the definition of "Objective-C object". The runtime recognizes anything with an <code>isa</code> sitting as its first member as an object, and we can take advantage of that and write a simple C++ class with a corresponding object interface so it can be messaged:</p> <pre><code>@interface CFIObject : NSObject - (void)doSomething; @end struct CFIObject_cxx { Class isa; public: CFIObject_cxx() : isa([CFIObject class]) {} ~CFIObject_cxx() { printf("I'm dying!"); } }; @implementation CFIObject - (void)doSomething { NSLog("I did something."); } @end </code></pre> <p>We can now instantiate an instance of our C++ object and wrap it in a smart pointer, which I'm going to purposefully split into two methods to illustrate the lifetime of the object:</p> <pre><code>void func() { // Instantiate a smart pointer with our fake object. std::unique_ptr&lt;CFIObject_cxx&gt; cppObj (new CFIObject_cxx()); id obj = (__bridge id)(cppObj.get()); // The runtime thinks we're an object. [obj doSomething]; // aaaand, it's out of scope. } int main(int argc, const char **argv) { func(); return 0; } </code></pre> <p>As one would expect, this prints:</p> <pre><code>2013-12-22 17:23:22.681 Test[77528:303] I did something I'm dying! </code></pre> <p>to the console.</p> <p>If need be, the destructor could be outfitted to call through to <code>-dealloc</code> to simulate proper object destruction, but I hope you see that all of this is just wholly unnecessary, especially with ARC getting smarter with each release of CLANG.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload