0

I can do this:

#include <vector>
#include <memory>
int main(int argc, char const *argv[]) {
    int size = 5;
    int *array = new int[size];
    load(array);
    std::vector<int> v(array, array+size);
    delete[] array;
}

And, with smart porter, this (alt1):

#include <vector>
#include <memory>
int main(int argc, char const *argv[]) {
    std::unique_ptr<int[]> array(new int[size]);
    load(array.get());
    std::vector<int> v(array.get(), array.get()+size);
}

And I was wondering, with all this smartness in place, if something even shorter (alt2) would be ok:

#include <vector>
#include <memory>
int main(int argc, char const *argv[]) {
    std::unique_ptr<int[]> array(new int[size]);
    load(array.get());
    std::vector<int> v(array);
}

But compiler says no:

c++ -std=gnu++14 -g -Wall -O3  -c -o main.o main.cpp
main.cpp:6:19: error: no matching constructor for initialization of 'std::vector<int>'
        std::vector<int> v(array);

So, alt1 is the shortest way to init std::vector with unique_ptr?

2
  • 4
    You are not initializing with unique_ptr. You are simply copying contents of an array into a vector. The fact that the memory occupied by that array is manged by an instance of unique_ptr is irrelevant. Commented Jul 22, 2018 at 3:02
  • std::unique_ptr is a wrapper that will automatically dispose of the referenced memory when it goes out of scope just so you don't have to call delete yourself by the end of the function. Since you did not allocate std::vector using a new operator, you simply don't need it at all. Plus as pointed out by others, creating an array here is redundant and makes no sense, std::vector will manage it's own array internally. Commented Jul 22, 2018 at 6:45

1 Answer 1

2

All of these are equivalent to std::vector<int> v(size); -- creating a vector of a specific size and default initializing all the members. All you are doing with the arrays and unique_ptrs is creating an array with default initialized members and then copying the array into a vector -- default initializing the array directly is simpler.

If you want to load into the vector, you can do that too:

std::vector<int> v(size);
load(&v[0]);
Sign up to request clarification or add additional context in comments.

2 Comments

Not quite. The original code is garbage-initializing all the elements; the code exhibits undefined behavior by way of accessing uninitialized objects. std::vector<int> v(size); on the other hand fills the vector with zeros.
Slightly modified the code. There is a function loading data into the array, I can’t change this so is not possible to go directly with the vector. Sorry for not mentioning this since the beginning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.