This question already has an answer here:
Consider following code:
class Shape
{
public:
virtual void introduceMe() = 0;
};
class Triangle : public Shape
{
public:
void introduceMe() override { std::cout << " I am a triangle \n"; }
};
Moreover consider my following smart pointer:
template<typename T>
class MyUnique_ptr
{
T* ptr;
public:
explicit MyUnique_ptr(T* p = nullptr)
{
ptr = p;
}
~MyUnique_ptr()
{
delete ptr;
}
}
Furthermore, consider this supplementary piece of code:
MyUnique_ptr<Shape> make_triangle()
{
MyUnique_ptr<Shape> x(new Triangle);
return x; //a- getting an error: implicit defined copy constructor is a deleted function. (But works if I implement a copy constructor)
}
struct Color {
float g;
};
Color test() {
Color c;
return c; //b- why this work whereas a) does not ?
}
And finally, here is how my main look like:
int main(int argc, char** argv)
{
MyUnique_ptr<Shape> a(new Triangle);
MyUnique_ptr<Shape> b(make_triangle()); // c- same error here. But works if I implement a move constructor and no copy constructor, why?
MyUnique_ptr<Shape> c(a); // d- same error here. But works if copy constructor is explicitly defined.
}
To resume: 1- in a) c) and d) I'm getting errors, saying the implicitly defined copy constructor is a deleted function. Why it is deleted? If I implement a copy constructor then everything works fine. Why the compiler is forcing me to provide a copy constructor?
2- If I implement a move constructor (and no copy constructor) then lines a) and c) will work. Why the compiler is forcing me defined move semantics (constructor)? Are there some cases in c++ (like my example above maybe) where move constructor or move assignment MUST explicitly be defined? Are they actually implicitly defined by the constructor? Thanks
Aucun commentaire:
Enregistrer un commentaire