简体   繁体   中英

Passing NSString* to a C++ reference parameter

Have an Objective-C++ function. (The file has the correct .mm extension).

int SPGetNumericAttribute(NSMutableString* line, NSString* &attr) {...}

Some code calls as follows:

NSString* queryAttr = nil;
int res = SPGetNameAttribute(line, queryAttr); <-- error

Compiler complains:

No matching function call for 'SPGetNameAttribute'.

Is there a technical reason why you can't pass an Objective-C object to a C++ reference parameter? My guess is something to do with ARC.

ARC needs to know how to handle the reference counting of the second parameter inside of the function. By default the parameter has autoreleasing type. Thus your variable queryAttr must have the autoreleasing ARC type

__autoreleasing NSString* queryAttr = nil;

or alternatively you can declare your function as

int SPGetNumericAttribute(NSMutableString* line, NSString* __strong &attr) { ... }

and the error disappears for strong variables. Tests with Instruments show that ARC seems to be handling this right, too. But then you may only use strong variables for this parameter.

I think it should be better, if you use a pointer instead:

int SPGetNumericAttribute(NSMutableString* line, NSString** attr) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM