简体   繁体   中英

Objective-C++ can't use vector push_back within enumerate block

bar.mm

#include <stdlib.h>
#include <string>
#include <vector>

+ (BOOL)addURIs:(NSArray<NSString *>*)URIs {
    std::vector<std::string> uris;
    uris.push_back("1234");    // works!

    [URIs enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        std::string str = std::string([obj UTF8String]);
        uris.push_back(str); // error: No matching member function for call to 'push_back'
    }];
    return YES;
}

I've currently using objective-c++ to bridge a C++ library to Objecitve-C.

I created a vector contains string and attempt to push_back another string.

Why the first push_back success and the second push_back comes up with error?

No matching member function for call to 'push_back'

Edit:

std::vector<std::string> *vector = {};
[URIs enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    std::string str = std::string([obj UTF8String]);
    vector->push_back(str);
}];

Using a pointer seems like to be a workaround.

Blocks capture local C++ variables by copying them with the copy constructor, and then they are const in the block See Reference:

Stack (non-static) variables local to the enclosing lexical scope are captured as const variables.

...

If you use any other C++ stack-based object from within a block, it must have a const copy constructor. The C++ object is then copied using that constructor.

This means that inside the block you can only call methods of the uris vector which are marked const (such as size() ).

You can use the __block storage specifier to allow the variable to be modified within the block.

// this will allow it to be modified within capturing blocks
__block std::vector<std::string> uris;

You could also just iterate the array with a loop, rather than a block.

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