简体   繁体   中英

Using unique_ptr and vector

I have this code:

v8::Handle<v8::Value> StartMethod(const v8::Arguments &args) {
    v8::HandleScope scope; // node_isolate
    int length = args.Length();
    std::vector<std::unique_ptr<char[]>> argv;
    for(int i=0;i<length;++i) {
        if(args[i]->IsString()) {
            v8::String::Utf8Value str(args[i]);
            const int strLen = ToCStringLen(str);
            if(strLen) {
                std::unique_ptr<char []> data(new char[strLen+1]);
                strcpy_s(data.get(), strLen+1, ToCString(str));
                argv.push_back(std::move(data));
            }
        }
    }
    return scope.Close(v8::Int32::New(MainMethod(argv.size(), &(argv[0]._Myptr))));
}

I am using std::move and it is working fine. When i do not use std::move it gives me compiler errors because of unavailability of assignment function.

But Does it guarantees that when vector changes its location, may be because of some internal re sizing and move objects around, nothing bad would happen ?

vector<T>::push_back gives the strong exception safety guarantee for move-only types if and only if the move construtor of T does not throw .

In your case T is a unique_ptr for array objects, whose move constructor is declared noexcept (§20.7.1.3), so you are indeed fine here: If the internal resizing of the vector throws a bad_alloc , the vector will remain unchanged and usable.

I am not sure if I got your question right, but under the assumption that std::vector doesn't have any unexpected behaviour, yes, it is garantueed. By executing std::move() you transfer the control over the underlaying pointer to the std::unique_ptr in the std::vector . From this point on it should behave like a std::vector<char*>

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