Reputation: 81
Assume the following piece of code to move an object of type A
into av
(vector):
#include <memory>
#include <vector>
struct A
{
~A() {};
std::unique_ptr<int> an_int;
};
int main(int argc, char* argv[])
{
std::vector<A> av;
av.push_back(A());
return 0;
}
This will fail to compile as is. However if I do not implement the destructor ~A() {}
, it will work just fine. The compiler hints at some missing (deleted) copy constructor
, but I fail to see where that applies here (as I am only doing move operations)
What is the relationship between the unique_ptr
and the custom destructor that makes the code fail to compile? is there a simple work around for this?
Thanks.
Upvotes: 2
Views: 210
Reputation: 19223
Defining a custom destructor disables generation of the default move constructor and move assignment operator. Thus push_back(const A&)
is used, but A
does not have copy constructors either since it has unique_ptr
member.
The solution is to manually define them as default
. But defining the move constructor disables the default constructor:
struct A
{
~A() {};
A()=default;
A(A&&)=default;
A& operator=(A&&)=default;
std::unique_ptr<int> an_int;
};
static_assert(std::is_nothrow_move_constructible_v<A>);
static_assert(std::is_nothrow_move_assignable_v<A>);
Upvotes: 4
Reputation: 98088
When you define a destructor the compiler does not generate a move/copy constructor since you just hinted that the construction/destruction of the object is not trivial. See this answer.
Upvotes: 2