Created
January 28, 2024 08:24
-
-
Save jasleon/81d2041c9a72c94cb1164e0d953ee630 to your computer and use it in GitHub Desktop.
C++ Object Lifetime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://godbolt.org/z/4xh9KEzx8 | |
#include <iostream> | |
namespace as { | |
struct lifetime { | |
lifetime() { std::cout << "lifetime default constructor\n"; } | |
lifetime(const lifetime &) { std::cout << "lifetime copy constructor\n"; } | |
lifetime(lifetime &&) noexcept { | |
std::cout << "lifetime move constructor\n"; | |
} | |
lifetime &operator=(const lifetime &) { | |
std::cout << "lifetime copy assignment operator\n"; | |
return *this; | |
} | |
lifetime &operator=(lifetime &&) noexcept { | |
std::cout << "lifetime move assignment operator\n"; | |
return *this; | |
} | |
~lifetime() { std::cout << "lifetime destructor\n"; } | |
}; | |
} // namespace as | |
int main() { | |
using as::lifetime; | |
std::cout << "Creating an object using the default constructor:\n"; | |
lifetime obj1; | |
std::cout << "\nCreating another object as a copy of the first one:\n"; | |
lifetime obj2 = obj1; | |
std::cout << "\nCreating a third object using the move constructor:\n"; | |
lifetime obj3 = std::move(obj2); | |
std::cout << "\nAssigning the second object to the third one using the " | |
"copy assignment operator:\n"; | |
obj3 = obj1; | |
std::cout << "\nAssigning the first object to the third one using the move " | |
"assignment operator:\n"; | |
obj3 = std::move(obj1); | |
std::cout << "\nExiting the main function, objects will be destroyed:\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment