Rule of Three/Five/Zero

Rule of Three

If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three.

Rule of Five

Because the presence of a user-defined destructor, copy-constructor, or copy-assignment operator prevents implicit definition of the move constructor and the move assignment operator, any class for which move semantics are desirable, has to declare all five special member functions:

class string
{
    char* cstring;
public:
    //constructor
    string(const char* arg)
     : cstring(new char[std::strlen(arg) + 1 ]) {
         std::strcpy(cstring, arg);
         std::cout<<"constructor called"<
#include"string.h"
#include
// tip 1 utility for std::move
#include

int main(){
    const char* a = "hello world";
    string s = string{a};
    string b = string{s};
    string c = string{ std::move(b) };
    string d{a};
    d = c;
    s = std::move(d);
    return 0;
}

output:
constructor called
copy constructor called
move constructor called
constructor called
copy assignment constructor called
copy constructor called
destructor called
move assignment constructor called
copy constructor called
destructor called
destructor called
destructor called
destructor called
destructor called

#include"string.h"
#include
#include

int main(){
    const char* a = "hello world";
    string b  = string{a};
    std::move(b);
    std::cout<<"move called"<

Rule of zero

Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the Single Responsibility Principle). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators.[1]

你可能感兴趣的:(Rule of Three/Five/Zero)