简体   繁体   English

使用unique_ptr和vector

[英]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. 我正在使用std::move ,并且工作正常。 When i do not use std::move it gives me compiler errors because of unavailability of assignment function. 当我不使用std :: move时,由于assignment函数不可用,它给了我编译器错误。

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 . 当且仅当T的移动构造函数未抛出时, vector<T>::push_back为仅移动类型提供强大的异常安全保证。

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. 在您的情况下, T是数组对象的unique_ptr ,其移动构造函数声明为noexcept (第2.0.7.1.3节),因此,您的确不错:如果向量的内部调整大小抛出bad_alloc ,则向量将保持不变且可用。

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. 我不确定我是否正确回答了您的问题,但是在std :: vector没有任何意外行为的假设下,是的,它是可靠的。 By executing std::move() you transfer the control over the underlaying pointer to the std::unique_ptr in the std::vector . 通过执行std::move()您可以将对底层指针的控制权转移到std::vectorstd::unique_ptr From this point on it should behave like a std::vector<char*> 从这一点来看,它的行为应类似于std::vector<char*>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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