strong/weak ptr in ARC and C++11

__strong / __weak in ARC vs shared_ptr / weak_ptr in C++11.

result

*** ARC ***
I'm CocoaPitcher, ball = <CocoaBall: 0x7f8809d00570>
I'm CocoaPitcher, ball = (null)
*** C++11 ***
I'm CppPitcher, ball = 7802300.
I'm CppPitcher, ball is null.

main.mm

#import <Foundation/Foundation.h>
#import "CocoaPitcher.h"
#import "CocoaBall.h"
#include "CppPitcher.h"
#include "CppBall.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSLog(@"*** ARC ***");
        CocoaPitcher *pitcher = [[CocoaPitcher alloc] init];

        @autoreleasepool {
            CocoaBall *ball = [[CocoaBall alloc] init];
            pitcher.ball = ball;
            [pitcher print];                
        }
        [pitcher print];
        
        NSLog(@"*** C++11 ***");
        std::shared_ptr<CppPitcher> cppPitcher(new CppPitcher);
        {
            std::shared_ptr<CppBall> ball(new CppBall);
            cppPitcher->ball = ball;
            cppPitcher->print();
        }
        cppPitcher->print();
    }
    return 0;
}

CocoaPitcher.h/m

#import <Foundation/Foundation.h>

@class CocoaBall;

@interface CocoaPitcher : NSObject

- (void)print;

@property (weak) CocoaBall *ball;

@end

#import "CocoaPitcher.h"
#import "CocoaBall.h"


@implementation CocoaPitcher
@synthesize ball;

- (void)print {
    NSLog(@"I'm %@, ball = %@", [self class], ball);
}
@end

CppPitcher.h/cpp

#include <memory>

class CppBall;

class CppPitcher {
public:
    void print();
    std::weak_ptr<CppBall> ball;
};

#include "CppPitcher.h"
#include "CppBall.h"

void CppPitcher::print(){
    printf("I'm CppPitcher, ");
    if (auto b = ball.lock()) {
        printf("ball = %x.\n", b.get());
    } else {
        printf("ball is null.\n");
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *