c++ - Resources management - vector and pointers -


i need store sequence of elements of type thirdpartyelm, , i'm using std::vector (or std::array if need fixed size sequence).

i'm wondering how should initialise sequence. first version creates new element , (if i'm right) creates copy of element when inserted in sequence:

for (int = 0; < n; i++) {    auto elm = thirdpartyelm();    // init elm..    my_vector.push_back(elm);  // my_array[i] = elm; } 

the second version stores sequence of pointers (or better smart pointers c++11):

for (int = 0; < n; i++) {    std::unique_ptr<thirdpartyelm> elm(new thirdpartyelm());    // init elm..    my_vector.push_back(std::move(elm));  // my_array[i] = std::move(elm); } 

which lightweight version?

please highlight errors.

avoid dynamic allocation whenever can. thus, prefer saving elements instead of smart-pointers them in vector.

that said, either fine, , if thirdpartyelem polymorphic, wouldn't have choice.

other considerations cost , possibility of moving , copying type, though don't worry.

there 2 refinements option 1 might worthwhile though:

  1. std::move new element place, less expensive copying (which might not possible).
    if type copyable , not movable (legacy, ask update), falls copying.

  2. try construct in-place, eliminate copy or move, , needless destruction.

for (int = 0; < n; i++) {    my_vector.emplace_back();    try {        auto&& elm = my_vector.back();        // init elm..    } catch(...) {        my_vector.pop_back();        throw;    } } 

if initialization cannot throw, compiler remove exception-handling (or can omit it).


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -