Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <exception>
- #include <memory>
- // External world
- typedef void *EXTERNAL_ONE;
- static EXTERNAL_ONE CreateExternalOne(long i) {
- std::cout << "Creating heavy object" << std::endl;
- return reinterpret_cast<EXTERNAL_ONE>(i);
- }
- static void ReleaseExternalOne(EXTERNAL_ONE resource) noexcept(false) {
- if (resource == nullptr) {
- throw std::exception();
- }
- std::cout << "Releasing heavy object" << std::endl;
- }
- static void DoSomethingUseful(EXTERNAL_ONE resource) {
- std::cout << "I am using " << reinterpret_cast<long>(resource) << std::endl;
- }
- // Defecate approach
- typedef std::unique_ptr<void, decltype(&ReleaseExternalOne)> SmartResource;
- static SmartResource Create(int i) {
- return SmartResource(CreateExternalOne(i + 22), &ReleaseExternalOne);
- }
- static void defecateApproach() {
- auto resource = Create(14);
- DoSomethingUseful(resource.get());
- }
- //Custom mover inspired by Gost
- class CustomWrapper {
- public:
- EXTERNAL_ONE m_externalOne;
- explicit CustomWrapper(EXTERNAL_ONE externalOne) : m_externalOne(externalOne) {
- }
- CustomWrapper(const CustomWrapper &other) = delete;
- CustomWrapper(CustomWrapper &&other) noexcept: m_externalOne(other.m_externalOne) {
- other.m_externalOne = nullptr;
- std::cout << "Moving, yey" << std::endl;
- }
- ~CustomWrapper() {
- if (m_externalOne) {
- ReleaseExternalOne(m_externalOne);
- } else {
- std::cout << "No need to delete dead one" << std::endl;
- }
- }
- };
- static void customApproachAcceptsMover(CustomWrapper wrapper) {
- DoSomethingUseful(wrapper.m_externalOne);
- }
- static void customApproach() {
- customApproachAcceptsMover(CustomWrapper(CreateExternalOne(99)));
- }
- int main() {
- defecateApproach();
- customApproach();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement