move

 avatar
unknown
c_cpp
a year ago
1.8 kB
16
Indexable
#include <iostream>

class A {
private:
    int x = 0;  // Regular integer

public:
    // Default Constructor
    A() : x(1) {
        std::cout << "Default constructor called. x = " << x << std::endl;
    }

    // Parameterized Constructor
    A(int val) : x(val) {
        std::cout << "Parameterized constructor called. x = " << x << std::endl;
    }

    // Copy Constructor
    A(const A& other) : x(other.x) {
        std::cout << "Copy constructor called. x = " << x << std::endl;
    }

    // Move Constructor
    A(A&& other) noexcept : x(std::move(other.x)) {
        std::cout << "Move constructor called. x = " << x << std::endl;
        other.x = 0;  // Optionally reset the moved-from object
    }

    // Copy Assignment Operator
    A& operator=(A other) {
        std::swap(x, other.x);  // Swap the contents with the copy
        std::cout << "Copy/Move assignment operator called. x = " << x << std::endl;
        return *this;
    }

    // Destructor
    ~A() {
        if (x != 0)
            std::cout << "Destructor called. x = " << x << std::endl;
    }

};

class B {
public:
    template<typename T>
    B(T x) : trackedResource_(std::make_shared<TrackedResourceModel<T>>(std::move(x)))
    {
        std::cout << "B: resource tracking constructor called " << std::endl;
    }

private:
    struct TrackedResourceConept {
        virtual ~TrackedResourceConept() = default;
    };
    template <typename T>
    struct TrackedResourceModel : TrackedResourceConept {
        TrackedResourceModel(T x) : data_(std::move(x)) {}
        T data_;
    };
    std::shared_ptr<const TrackedResourceConept> trackedResource_;
};

B convert(A&& a) {
    return B(std::move(a));
}

int main() {
    A a {42};
    auto b = convert(std::move(a));
    auto x = b;
    auto y = b;
    auto z = b;
}
Editor is loading...
Leave a Comment