简体   繁体   中英

Why can I move an object with deleted move constructor and assignment operator?

I have the following definitions:

struct FileDescriptor {
    explicit FileDescriptor(int fd) : desc(fd), is_open(true) {}

    explicit operator int() { return desc; }

    FileDescriptor(const FileDescriptor &) = delete;

    FileDescriptor(FileDescriptor &&) = delete;

    FileDescriptor &operator=(const FileDescriptor &) = delete;

    FileDescriptor &operator=(FileDescriptor &&) = delete;

    ~FileDescriptor() {
        if (is_open) {
            close(desc);
        }
    }

    int desc;
    bool is_open;
};

std::string capture_out(FileDescriptor &&fd) {
    /* some code */
}

As you can see, the move constructor and assignment operator of the FileDescriptor structure are explicitly deleted. However, the following code compiles.

/* some code */
FileDescriptor fdhERR(6);

auto sERR = capture_out(std::move(fdhERR));
/* some code */

I am not very familiar with the intricacies of rvalue, but such behavior seems counterintuitive. Why does it happen?

capture_out() takes an rvalue reference as its parameter, but it is still just a reference nonetheless. std::move() is just a typecast to a reference, it doesn't actually move anything. Your example constructs only one FileDescriptor object and then passes it by reference to capture_out() , there is no second object being constructed or assigned to, so your deleted constructors and deleted operators are not called. Nothing is actually being copied or moved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM