vendredi 4 août 2023

Understanding the Consequences of Moving and Accessing Resources in C++ Destructors

I have the following code to provide context for my question. When move_test() is called within main(), a will be moved first, causing a._str to be moved and then destructed. However, I am attempting to use a._str within the destructor. Can someone please verify the following assumption? Thank you!

a._str has now been moved and is in an undefined state, and attempting to access it could potentially result in issues.

#include <iostream>
#include <string>
struct A { 
    A(A&& other)
        : _str(std::move(other._str)) {
            std::cout<<"A move constructed"<<std::endl;
        }
    
    ~A() {
        // _str has been moved, but accessed here, undefined behaviour?
        _str = "destructor called";
        std::cout<<_str<<std::endl;
    }

    static A move_test() {
        A a("hey");
        return std::move(a);
    }
    std::string _str;
private:
    A(const std::string s) : _str(s) {}
};

int main() {
    A b = A::move_test();
    b._str = "longer string";
    std::cout<<b._str<<std::endl;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire