-
-
Save g-1/cf753752774967c4a9fa to your computer and use it in GitHub Desktop.
ARC環境下でのメモリの振る舞い
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//定義 | |
@implementation TestDestructor | |
- (id)init{ | |
self = [super init]; | |
NSLog(@"a"); | |
return self; | |
} | |
- (void)dealloc{ | |
NSLog(@"b"); | |
} | |
@end | |
//実行 | |
{ | |
TestDestructor *test = [[TestDestructor alloc] init]; | |
NSLog(@"c"); | |
} | |
NSLog(@"d"); | |
//実行結果 | |
2011-12-09 01:07:30.627 ARC[626:f803] a | |
2011-12-09 01:07:30.631 ARC[626:f803] c | |
2011-12-09 01:07:30.633 ARC[626:f803] b | |
2011-12-09 01:07:30.635 ARC[626:f803] d | |
//例外時はどうなるか? | |
//test | |
{ | |
TestDestructor *test = [[TestDestructor alloc] init]; | |
@throw [NSException exceptionWithName:@"test" reason:nil userInfo:nil]; | |
NSLog(@"c"); | |
} | |
NSLog(@"d"); | |
//実行結果 | |
2011-12-09 01:56:11.638 ARC[722:f803] a | |
2011-12-09 01:56:11.642 ARC[722:f803] test | |
//つまりブロックを抜けているが、deallocは呼ばれない | |
//autoreleaseとの比較 | |
//実行 | |
{ | |
TestDestructor *test = [[[TestDestructor alloc] init] autorelease]; | |
NSLog(@"c"); | |
} | |
NSLog(@"d"); | |
//実行結果 | |
2011-12-09 02:06:58.084 Sample[843:f803] a | |
2011-12-09 02:06:58.086 Sample[843:f803] c | |
2011-12-09 02:06:58.087 Sample[843:f803] d | |
2011-12-09 02:06:58.092 Sample[843:f803] b | |
//デストラクタというよりもファイナライザ的な解放処理 | |
//エラー時 | |
2011-12-09 02:17:54.364 Sample[924:f803] a | |
2011-12-09 02:17:54.367 Sample[924:f803] test | |
2011-12-09 02:17:54.368 Sample[924:f803] b | |
//autopool releaseのときにメモリ回収は可能 | |
//ARC環境下では例外ジャンプが@autoreleasepoolブロック内でも回収されなかった。この辺りがC++のデストラクタの挙動と異なる | |
//C++で同等のコードを書いたとき | |
class CppDestructor | |
{ | |
public: | |
CppDestructor(){ | |
NSLog(@"a"); | |
} | |
~CppDestructor(){ | |
NSLog(@"b"); | |
} | |
void test(){ | |
} | |
}; | |
{ | |
CppDestructor test; | |
@throw [NSException exceptionWithName:@"test" reason:nil userInfo:nil]; | |
NSLog(@"c"); | |
} | |
NSLog(@"d"); | |
2011-12-09 02:33:56.531 Sample[1121:f803] a | |
2011-12-09 02:33:56.535 Sample[1121:f803] b | |
2011-12-09 02:33:56.536 Sample[1121:f803] test | |
//例外でスコープを抜けた時点でデストラクタが呼ばれる |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment