Re: GC pros and cons
Re: GC pros and cons
- Subject: Re: GC pros and cons
- From: Michael Ash <email@hidden>
- Date: Sat, 27 Jun 2009 00:27:00 -0400
On Fri, Jun 26, 2009 at 10:24 PM, James Gregurich<email@hidden> wrote:
> hehe. oh yes they do. You can put any TYPE you want in shared_ptr<>. If you want to put a posix file descriptor in it, just use close() as the custom deleter. works great. In fact, I guard SQLite db handles with shared_ptr.
>
> Here is how you do it:
>
> std::string tmpDbName("test.db");
> sqlite3* tmpDbPtr = NULL;
> boost::shared_ptr<sqlite3> tmpDbSPtr;
> int tmpResult = sqlite3_open_v2(tmpDbName.c_str(), &tmpDbPtr, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, statVSNamePtr);
>
> if(tmpResult != SQLITE_OK)
> {
> //handle error
> return;
> }
>
> tmpDbSPtr.reset(tmpDbPtr, sqlite3_close);
>
>
> this code is completely exception safe and won't leak the db handle under any circumstances.
Normally this would be a silly nitpick, but given the context of the
discussion, I think it's important to mention.
Your code is *not* completely exception-safe in Objective-C++ on the
Mac 32-bit runtime.
On this runtime (but fortunately not on the "modern" runtime found on
the iPhone and 64-bit processes on the Mac) the Objective-C exception
model is *not* unified with the C++ exception model. This means that
throwing an Objective-C exception through this code will not invoke
the objects' destructors and thus will not deallocate your resource.
Now, Objective-C exceptions are fairly rare and most Cocoa programmers
treat them as programming errors to be fixed rather than runtime
errors to be handled, but it's still something that ought to be kept
in mind.
The same goes for throwing C++ exceptions through Objective-C code.
Objective-C doesn't have destructors, but for example you will not
unlock the lock held in a @synchronized block, and various other
things can go wrong. In general, you should keep things well separated
and just not allow exceptions to be thrown through code from the
"other" language.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden