Reputation: 1678
I have following classes: Class A with deleted copy constructor.
class A
{
public:
explicit A(int i_a) {a = i_a;};
~A(){};
private:
A(const A&) = delete;
A& operator=(const A&) = delete;
int a;
};
and Class B with a unique_ptr member.
class A;
class B
{
public:
B(int i_b);
~B() {};
private:
std::unique_ptr<A> p_b;
};
and B.cpp:
B::B(int i_b)
{
p_b = std::make_unique<A>(A(i_b));
}
I am receiving this error while making unique_ptr of class A:
'A::A': cannot access private member declared in class 'A'
Can someone please explain me why I am receiving this error? I know that by commenting this line "A(const A&) = delete;" error will be resolved. But I am looking for some explanation.
Upvotes: 1
Views: 1470
Reputation: 22219
p_b = std::make_unique<A>(A(i_b));
In this line you are trying to call copy constructor, which you have delete
d (or move constructor, which is not declared)
Instead, you should use:
p_b = std::make_unique<A>(i_b);
Or you could declare move constructors for your class:
class A
{
public:
explicit A(int i_a) {a = i_a;};
A(A&&) = default;
A& operator=(A&&) = default;
~A(){};
private:
A(const A&) = delete;
A& operator=(const A&) = delete;
int a;
};
std::make_unique
will call a constructor of a given class, passing any arguments it has received as they are. So, if you pass an object of type A
, it will try to use constructor which takes an argument of type A
- i.e. copy constructor or move constructor.
Because you have declared copy constructor, move constructor was not automatically generated, so it couldn't have been used by std::make_unique
Upvotes: 7