I have the following sample:
#include <vector>
class noncopyable {
protected:
noncopyable() {}
~noncopyable() {}
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
noncopyable(noncopyable&&) = default;
noncopyable& operator=(noncopyable&&) = default;
};
class C1 : private noncopyable {
public:
C1() { }
~C1() { }
};
int main() {
std::vector<C1> v;
v.emplace_back();
return 0;
}
I thought it should work since C1
should be movable since it's base class is and it has no data members. Instead, I got an an error (using clang++):
error: call to implicitly-deleted copy constructor of 'C1'
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
.
.
.
note: in instantiation of function template specialization 'std::vector<C1, std::allocator<C1> >::emplace_back<>' requested here
v.emplace_back();
^
note: copy constructor of 'C1' is implicitly deleted because base class 'noncopyable' has a deleted copy constructor
class C1 : private noncopyable {
^
note: 'noncopyable' has been explicitly marked deleted here
noncopyable(const noncopyable&) = delete;
Doing a little research (http://ift.tt/V6FbVl) revealed that if there is a user-defined destructor then no implicit move-constructor will be defined. This seemes to be the problem here, since C1
has a destructor, the move-constructor does not get defined. Sure enough, if I either remove the destructor or add C1(C1&&) = default;
to C1
then it works.
So far so good.
The problem was that the error message didn't mention ~C1()
or the move-constructor. It said it was trying to call the copy constructor, which was deleted in the base class. So I tried changing the delete
ed functions in noncopyable
to be default
ed instead, and (surprise!), that also solved the error.
So my question is, what does this last thing have to do with the error or it's correction? If there is a destructor, what is the difference if the base class has the copy-constructor or not?
Aucun commentaire:
Enregistrer un commentaire