How the compile error below can be explained?
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class A{
unique_ptr<vector<short>> v;
public:
A(){
v = unique_ptr<vector<short>>(new vector<short>());
cout << "A()" << endl;
}
A(const A& a) : A(){
cout << "A(const A& a)" << endl;
}
};
int main() {
A a1; // prints A()
A a2 = a1; // prints A() then A(const A& a)
A& a3 = a1; // prints nothing
a3 = a1; // compile time error: use of deleted function ‘A& A::operator=(const A&)
return 0;
}
Actually, why A& a3 = a1
is ok and a3 = a1
is not? Also, which overloaded version of the operator= is being used and how could it be properly implemented to avoid this kind of problem?
In the line
a3 = a1;
you are invoking a deleted operator=
(remember that unique_ptr
is non-copyable). g++ spits out the error for you:
error: use of deleted function 'A& A::operator=(const A&)'
Whereas in the line
A& a3 = a1;
there is no copy made, you only initialize a reference.
You may want to move your pointer, like
a3 = std::move(a1);
Unfortunately, it won't work, since you explicitly declared a copy constructor, and this prevents the compiler from generating the default move constructor and assignment operator. Solution: declare the move assignment operator and move constructors as =default;
,
A& operator=(A&&) = default;
A(A&&) = default;
and the line a3 = std::move(a1)
above will work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.