LoginSignup
3
3

More than 5 years have passed since last update.

ObjCの配列は参照渡しなので要素の変更が(デフォルトで)伝播する

Posted at

ObjCでは@[a,b][1]に対する変更が元の変数に伝わるのに対し、C++では、std::vector<std::string>({a,b})[1]に対する変更は元の変数には伝わらない。*(std::vector<std::string*>({&a,&b})[1])のように、ポインタを介さなければならない。
いやまあ、単に参照渡しと値渡しの違いだけなんですが。

何が嬉しいかというと、たとえば2つのUILabelがあって、[@[a,b][n%2] setText:@"1"];とかやるのが容易ですよねってことで。

array_propagation.mm
#import <Foundation/Foundation.h>
#import <iostream>
#import <string>
#import <vector>

int main(){
    std::cout<<"ObjC"<<std::endl;
    {
        id myPool = [[NSAutoreleasePool alloc] init];

        NSMutableString *a=[NSMutableString stringWithString:@"a"];
        NSMutableString *b=[NSMutableString stringWithString:@"b"];
        [@[a,b][1] setString:@"c"];
        NSLog(@"%@ %@",a,b);

        [myPool drain];
    }
    std::cout<<"C++"<<std::endl;
    {
        std::string a="a";
        std::string b="b";
        std::vector<std::string>({a,b})[1][0]='c';
        std::cout<<a<<" "<<b<<std::endl;
        (*(std::vector<std::string*>({&a,&b})[1]))[0]='c';
        std::cout<<a<<" "<<b<<std::endl;
    }
    return 0;
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3