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?
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 ofunique_ptris irrelevant.std::unique_ptris a wrapper that will automatically dispose of the referenced memory when it goes out of scope just so you don't have to calldeleteyourself by the end of the function. Since you did not allocatestd::vectorusing anewoperator, 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::vectorwill manage it's own array internally.