// TODO Implement the methods of the FileDes" /> // TODO Implement the methods of the FileDes" /> // TODO Implement the methods of the FileDes"/>

Object of type 'net::FileDescriptor' cannot be assigned because its copy assignment operator is implicitly deleted

20 views Asked by At

Here is my code of filedescriptor.cpp:

#include <unistd.h>
#include "filedescriptor.h"
#include <utility>

// TODO Implement the methods of the FileDescriptor class as given in the filedescriptor.h header.
net::FileDescriptor::FileDescriptor(){}

net::FileDescriptor::FileDescriptor(int fd) {
fd_ = fd;
}
net::FileDescriptor::FileDescriptor(FileDescriptor& fd){
fd_ = fd.fd_;
}
net::FileDescriptor::FileDescriptor(FileDescriptor&& fd) noexcept{
fd_ = std::exchange(fd.fd_, -1);
}

net::FileDescriptor::~FileDescriptor(){
if (fd_.has_value() && *fd_ != -1) {
    close(*fd_);
}
}


int net::FileDescriptor::unwrap() const {
return fd_.value_or(-1);
}

//with this filedescriptor.h: 
#pragma once

#include <optional>

namespace net {

/// Wrapper for a Linux style file descriptor. It represents a potentially empty file descriptor.
/// The wrapper represents a unique ownership model, i.e. the file descriptor will get invalided
/// with the end of the lifetime of the object.
///
/// The following code should help you understand the ownership model:
/// ```cpp
/// auto fdraw {get_socket_fd_from_somewhere()};
/// {
///     FileDescriptor fd{fdraw};
///
///     // use fd, do whatever with it
/// }
/// // fd should not be usable anymore
/// ```
class FileDescriptor {
public:
/// Default constructor for empty file descriptor
FileDescriptor();

/// Construct from a integer file descriptor returned from the C API, take ownership of the
/// descriptor
explicit FileDescriptor(int fd);

/// Close the file descriptor (if present and valid)
/// Check out: close(3)
~FileDescriptor();

// TODO: Implement both copy and move constructors and assignment operators for the ownership        model
//       described in the class description.
FileDescriptor(FileDescriptor&& fd) noexcept;

FileDescriptor(FileDescriptor& fd);
/// Return the underlying file descriptor, if not present return -1 (this is quite standard for
/// linux systems)
int unwrap() const;

private:
std::optional<int> fd_ {};
};
} // namespace net

Now, when I am trying to call: fd_ = FileDescriptor(-1); in other code parts, I get the following error: "Object of type 'net::FileDescriptor' cannot be assigned because its copy assignment operator is implicitly deleted" Please help me to solve this error.

I tried to initialize the filedescriptor with the value of -1 and got an error.

0

There are 0 answers