The default constructor is sort of the odd man out here. Whether or not you have a default construct doesn't necessarily have any relationship to whether you write the others (although, writing a move constructor without a default constructor can be hard in practice).
In most cases you should try to follow the Rule of Zero (http://en.cppreference.com/w/cpp/language/rule_of_three, http://www.nirfriedman.com/2015/06/27/cpp-rule-of-zero/), which means that you would not write any of these member functions for your class. Instead, choose members that correctly express the ownership semantics you want for various resources. A member std::vector
correctly handles copying and movement the way you would want, so a class with such a member wouldn't necessarily need any special members. If you tried to use a raw pointer that was created with new[]
, however, as an array, then you would have many of these issues to deal with, and would need to write special member functions.
If you need to write one, you should explicitly think about all of them, but it doesn't mean you have to write all of them. Sometimes you may want to =default
or =delete
some of them. A quick example:
template <class T>
copy_ptr {
copy_ptr() = default;
copy_ptr(copy_ptr&&) = default;
copy_ptr& operator=(copy_ptr&&) = default;
copy_ptr(const copy_ptr& other)
: m_resource(make_unique<T>(*other.m_resource)
{}
copy_ptr& operator=(const copy_ptr& other) {
m_resource = make_unique<T>(*other.m_resource);
}
// define operator*, etc
std::unique_ptr<T> m_resource;
};
This is a pointer, that instead of being uncopyable like unique_ptr
, makes a deep copy of the object that it holds. However, we were able to use the default constructor, move operators, and destructors "as-is" from unique_ptr
, so we defaulted them. We only rewrote the copy operations, doing the minimum work.
Basically, the idea with special operators in C++ is to push them "downwards", into smaller objects/classes. Which are typically solely responsible for managing that resource. Bigger classes that coordinate business logic should try very hard to defer resource management concerns to members.