#include <iostream>
using namespace std;
class MyClass {
public:
int* x; // Using a pointer to demonstrate move semantics
// Constructor
MyClass(int value) {
x = new int(value); // Dynamic memory allocation
cout << "Constructor called! Value is: " << *x << endl;
}
// Copy constructor
MyClass(const MyClass &obj) {
x = new int(*obj.x); // Deep copy of the resource
cout << "Copy constructor called! Copied value is: " << *x << endl;
}
// Move constructor
MyClass(MyClass &&obj) noexcept {
x = obj.x; // Transfer ownership of the resource
obj.x = nullptr; // Leave the original object in a valid but empty state
cout << "Move constructor called! Moved value is: " << *x << endl;
}
// Destructor
~MyClass() {
if (x != nullptr) {
cout << "Destructor called! Deleting value: " << *x << endl;
delete x; // Clean up the resource
}
else {
cout << "Destructor called! Nothing to delete." << endl;
}
}
};
int main() {
MyClass obj1(10); // Calls constructor
MyClass obj2 = obj1; // Calls copy constructor
MyClass obj3 = std::move(obj1); // Calls move constructor
return 0;
}
/*
The noexcept specifier in C++ is used to indicate whether a function or constructor is guaranteed not to throw exceptions.
When you declare a function or constructor as noexcept, you're telling the compiler and the runtime system that this
function will not throw exceptions. This can lead to performance optimizations and more robust code.
Why noexcept is Important:
Performance: When a function is marked noexcept, the compiler can make optimizations, such as skipping certain checks that it would
otherwise perform in case of exceptions.
Move Semantics: The standard library uses move constructors and move assignment operators that are noexcept-qualified. If a move
constructor is not marked noexcept, containers like std::vector may fall back to copying elements during operations like resizing,
which can be less efficient.
*/
To embed this project on your website, copy the following code and paste it into your website's HTML: