Files
external_libcamera/include/libcamera/file_descriptor.h
Laurent Pinchart 206fada99d libcamera: file_descriptor: Implement move semantics for constructor
The FileDescriptor class, when constructed from a numerical file
descriptor, duplicates the file descriptor and takes ownership of the
copy. The caller has to close the original file descriptor manually if
needed. This is inefficient as the dup() and close() calls could be
avoided, but can also lead to resource leakage, as recently shown by
commit 353fc4c223 ("libcamera: v4l2_videodevice: Fix dangling file
descriptor").

In an attempt to solve this problem, implement move semantics for the
FileDescriptor constructor. The constructor taking a numerical file
descriptor is split in two variants:

- A "fd copy" constructor that takes a const lvalue reference to a
  numerical file descriptor and duplicates it (corresponding to the
  current behaviour).
- A "fd move" constructor that takes a rvalue reference to a numerical
  file descriptor and takes ownership of it.

Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Reviewed-by: Niklas Söderlund <niklas.soderlund@ragnatech.se>
Reviewed-by: Naushir Patuck <naush@raspberrypi.com>
2020-05-19 18:07:49 +03:00

49 lines
996 B
C++

/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
* Copyright (C) 2019, Google Inc.
*
* file_descriptor.h - File descriptor wrapper
*/
#ifndef __LIBCAMERA_FILE_DESCRIPTOR_H__
#define __LIBCAMERA_FILE_DESCRIPTOR_H__
#include <memory>
namespace libcamera {
class FileDescriptor final
{
public:
explicit FileDescriptor(const int &fd = -1);
explicit FileDescriptor(int &&fd);
FileDescriptor(const FileDescriptor &other);
FileDescriptor(FileDescriptor &&other);
~FileDescriptor();
FileDescriptor &operator=(const FileDescriptor &other);
FileDescriptor &operator=(FileDescriptor &&other);
bool isValid() const { return fd_ != nullptr; }
int fd() const { return fd_ ? fd_->fd() : -1; }
FileDescriptor dup() const;
private:
class Descriptor
{
public:
Descriptor(int fd, bool duplicate);
~Descriptor();
int fd() const { return fd_; }
private:
int fd_;
};
std::shared_ptr<Descriptor> fd_;
};
} /* namespace libcamera */
#endif /* __LIBCAMERA_FILE_DESCRIPTOR_H__ */