discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: GNUstep and valgrind


From: David Chisnall
Subject: Re: GNUstep and valgrind
Date: Sun, 18 Mar 2018 10:44:56 +0000

On 17 Mar 2018, at 18:06, amon <address@hidden> wrote:
> 
> Just noticed this while researching... it does not appear to be
> possible to create an NSHost object that is *not* autoreleased.
> Is this true or did I miss something in the docs?

As Fred pointed out earlier, whether you create autoreleased instances doesn’t 
matter.  You can simply write:

NSHost *host;
@autoreleasepool
{
        host = [[NSHost hostWithAddress: someAddress] retain];
}

And now you will have a non-autoreleased instance and all temporary objects 
constructed by the NSHost class will be destroyed (unless otherwise 
referenced).  In ARC mode, you can simply write:

NSHost *host;
@autoreleasepool
{
        host = [[NSHost hostWithAddress: someAddress] retain];
}

If you want to simplify this, then you can wrap it up in a function that takes 
a block:

static inline id get_retained(id(^block)())
{
        @autoreleasepool
        {
                return block();
        }
}

Which you can then use as follows:

NSHost *host = get_retained(^() { return [NSHost currentHost]; });

Or, in Objective-C++ you can do it in a more typesafe way using templates:

#import <Foundation/Foundation.h>

template<typename T>
auto get_retained(T block) -> decltype(block())
{
        @autoreleasepool
        {
                return block();
        }
}

Which you can then use in exactly the same way, or using C++ lambdas (which 
have slightly less horrible syntax):

NSHost *host = get_retained([]{ return [NSHost currentHost]; });

David




reply via email to

[Prev in Thread] Current Thread [Next in Thread]