cpp_prac/junk/1.cc

64 lines
1.6 KiB
C++
Raw Normal View History

2025-01-10 08:15:31 +01:00
#include <iostream>
using std::cout;
// Rule of three:
// If a class requires a user-defined destructor, a user-defined copy
2025-01-11 17:54:29 +01:00
// constructor, or a user-defined copy assignment operator, it almost
// certainly requires all three.
2025-01-10 08:15:31 +01:00
//
// Rule of five:
// Because the presence of a user-defined (include = default or = delete
2025-01-11 17:54:29 +01:00
// declared) 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:
2025-01-10 08:15:31 +01:00
struct A {
2025-01-11 17:54:29 +01:00
A() = default;
/* Constructor */
A(const int &x) { val = x; }
/* Copy constructor */
A(A &other) { other.val = this->val; }
/* Move constructor */
A(A &&other) { other.val = this->val; }
/* Copy assignment operator */
A &operator=(const A &other) { return *this; }
~A() {}
void print() { cout << "A(" << val << ")"; }
int val;
2025-01-10 08:15:31 +01:00
};
struct B {
2025-01-11 17:54:29 +01:00
B(int x) { a = A(x); }
// B(int x) : a(x) {};
void print() {
cout << "B(";
a.print();
cout << ")";
}
A a;
2025-01-10 08:15:31 +01:00
};
int main() {
2025-01-11 17:54:29 +01:00
B b(10);
b.print();
cout << "\n";
2025-01-10 08:15:31 +01:00
}
struct K {
2025-01-11 17:54:29 +01:00
K() = default;
/* Constructor */
K(const int &x) { val = x; }
/* Copy constructor */
K(K &other) : K(other.val) {}
/* Move constructor */
K(K &&other) : K(other.val) {}
/* Copy assignment operator */
K &operator=(const K &other) { return *this; }
~K() {}
void print() { cout << "K(" << val << ")"; }
int val;
2025-01-10 08:15:31 +01:00
};