The compiler reminds me that I'm using a deleted function . https://ideone.com/3YAIlA
#include <memory>
using namespace std;
class foo
{
public:
unique_ptr<int> p;
~foo()
{
}
};
int main()
{
foo a, b;
a = move(b);
return 0;
}
compilation info
prog.cpp: In function 'int main()':
prog.cpp:15:4: error: use of deleted function 'foo& foo::operator=(const foo&)'
a = move(b);
prog.cpp:3:7: note: 'foo& foo::operator=(const foo&)' is implicitly deleted because the default definition would be ill-formed:
class foo
prog.cpp:3:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
In file included from /usr/include/c++/5/memory:81:0,
from prog.cpp:1:
/usr/include/c++/5/bits/unique_ptr.h:357:19: note: declared here
unique_ptr& operator=(const unique_ptr&) = delete;
If I remove the destructor ,my code compiles fine. https://ideone.com/UFB18P
A Destructor is useful for when your classes contain Dynamically Allocated Memory. If your classes are simple and don't have 'DAM', then it's safe to not use a Destructor. In addition, read about the Rule Of Three. You should also add a copy constructor and an overloaded = operator if your class is going to have 'DAM'.
We know that if a destructor is not provided, the compiler will generate one. This means that anything beyond simple cleanup, such as primitive types, will require a destructor.
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
The destructors of base classes and members are called in the reverse order of the completion of their constructor: The destructor for a class object is called before destructors for members and bases are called. Destructors for nonstatic members are called before destructors for base classes are called.
Because that's what the standard says. When you start adding special member functions, you inhibit the automatic generation of some of the other ones. This is in the same category of rules as how writing a non-default constructor means a default one won't be automatically generated for you.
Add this:
foo& operator=(foo&&) = default;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With