I have encountered an error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr >' when compile code similar to below using c++ -std=c++14 unique_ptr_vector.cpp -o main
Here is a simplified version:
header file 'my_header.h':
#include <iostream>
#include <string>
#include <memory>
#include <vector>
class A{
public:
A() : n(0) {}
A(int val) : n(val) {}
A(const A &rhs): n(rhs.n) {}
A(A &&rhs) : n(std::move(rhs.n)) {}
A& operator=(const A &rhs) { n = rhs.n; return *this; }
A& operator=(A &&rhs) { n = std::move(rhs.n); return *this; }
~A() {}
void print() const { std::cout << "class A: " << n << std::endl; }
private:
int n;
};
namespace {
std::vector<std::unique_ptr<A>> vecA = {
std::make_unique<A>(1),
std::make_unique<A>(2),
std::make_unique<A>(3),
std::make_unique<A>(4)
};
}
And my src file unique_ptr_vector.cpp
:
#include "my_header.h"
using namespace std;
int main()
{
for(const auto &ptrA : vecA){
ptrA->print();
}
return 0;
}
Do I really need to use push_back(std::make_unique<A>(<some_number>))
individually for each component,
Or what would be a preferred way to populate a container in a header? Or is this a bad idea in general?
I have seen problems around like this one, this one, and this one.
I know now Initialization list seems impossible. but what do people normally do with container<unique_ptr>
. Should I just simply avoid initialize that in a header...