mardi 1 mars 2022

What happens internally when std::move is called?

I wanted to know what exactly happens internally when we call std::move on an object. For example:

class Holder {
    int* m_ptr;
    int m_size;
public:
    Holder(int size) : m_size(size),
        m_ptr(size ? new int[size] : 0) {
        cout << "Constructor\n";
    }
    ~Holder() {
        cout << "Destructor\n";
        delete[] m_ptr;
    }

    Holder(const Holder& other) {
        cout << "Copy Constructor\n";
        m_ptr = new int[other.m_size];
        std::copy(other.m_ptr, other.m_ptr + other.m_size, m_ptr);
        m_size = other.m_size;
    }

    void swap(Holder& other) noexcept {
        std::swap(this->m_ptr, other.m_ptr);
        std::swap(this->m_size, other.m_size);
    }

    Holder& operator=(const Holder& other) {
        cout << "Copy Assignment\n";
        Holder(other).swap(*this);
    }

    Holder(Holder&& other) : m_ptr(other.m_ptr), m_size(other.m_size) {
        cout << "Move Constructor\n";
        other.m_ptr = nullptr;
        other.m_size = 0;
    }

    Holder& operator=(Holder&& that) noexcept {
        cout << "Move Assignment\n";
        Holder(std::move(that)).swap(*this);
        return *this;
    }
};


Holder createHolder(int size) {
    return Holder(size);
}

int main(void) {
    Holder h = createHolder(1000);
    return 0;
}

Gives the output as when compiled with '-fno-elide-constructors':

Constructor
Move Constructor
Destructor
Move Constructor
Destructor
Destructor

Since we are returning from a function createHolder and the return object is on the stack, how does the main function still receives it? Not getting exactly what happens internally in memory.

Thanks.

1 commentaire:

  1. Casino Games Near Me | Mapyro
    MapYRO Casino has everything 시흥 출장샵 you need to know about the area's casinos and other things to do, 영주 출장샵 from table games 상주 출장샵 to poker to online 충주 출장안마 scratchcards. 통영 출장샵

    RépondreSupprimer