Skip to content

Instantly share code, notes, and snippets.

@madmongo1
Created September 21, 2016 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madmongo1/c18a3a567055481762b123629b0135d0 to your computer and use it in GitHub Desktop.
Save madmongo1/c18a3a567055481762b123629b0135d0 to your computer and use it in GitHub Desktop.
//
// main.mm
// foo2
//
// Created by Richard Hodges on 21/09/2016.
// Copyright © 2016 Richard Hodges. All rights reserved.
//
#include <vector>
#import <Foundation/Foundation.h>
@interface Thing : NSObject
@end
@implementation Thing
@end
extern void foo(Thing*);
int main()
{
// declare my vector
std::vector<__weak Thing*> myThings;
// store a weak reference in it
Thing* t = [[Thing alloc]init];
myThings.push_back(t);
// ... some time later ...
for(auto weak : myThings) {
Thing* strong = weak; // safely lock the weak pointer
if (strong) {
foo(strong);
// use the locked pointer
}
}
t = nullptr;
for(auto weak : myThings) {
Thing* strong = weak; // safely lock the weak pointer
if (strong) {
foo(strong);
// use the locked pointer
}
}
}
void foo(Thing*p)
{
NSLog(@"%@", [p className]);
}
// expected: one log output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment