当对象表示硬件组件时,我应该使用指向对象还是对象的指针?

Should I use a pointer to an object or an object when the object represents an hardware component?

我有一个名为 Camera 的 class,它在构造函数中使用 v4l2_open 等打开相机。析构函数进行一些清理并使用 v4l2_close.

关闭文件描述符

当相机崩溃时,我做的是删除对象,然后创建一个新对象:

Camera *camera = new Camera();
(...)
if (crash) {
  delete camera;
  camera = new Camera();
}

这是 C++ 中 new/delete 的正确用法之一吗?

不,这里不保证使用 newdelete。如果您的相机“变坏”并且您希望处理掉它以换一台新相机,只需分配一个新相机即可。

const std::string device {"/dev/cameras/front"};  // whatever
Camera camera {device};
// do something...
if (camera.bad())
  camera = Camera {device};  // replace by a new one

您可能需要 Camera class 的 overload the assignment operator 才能正常工作。由于 Camera class 是资源拥有的,它不应该是可复制的,而是可移动的。我不知道你是如何与硬件对话的,所以我对下面的例子做了一些改进,但它应该能让你正确地了解如何实现你的类型。

extern "C"
{
  // I have made these up...
  int camera_open(const char *);
  int camera_close(int);
}

class Camera
{

private:

  // Initially set to arbitrary nonsensical values.
  std::string device_ {};
  int fd_ {-1};

public:

  Camera() noexcept
  {
  }

  Camera(const std::string& device) : device_ {device}
  {
    this->open();
  }

  ~Camera() noexcept
  {
    try
      {
        this->close();
      }
    catch (const std::exception& e)
      {
        // Cannot throw from a destructor...
        std::cerr << e.what() << std::endl;
      }
  }

  Camera(const Camera&) = delete;  // not copy-constructible

  Camera(Camera&& other) : Camera {}
  {
    swap(*this, other);
  }

  Camera& operator=(const Camera&) = delete;  // not copy-assignable

  Camera&
  operator=(Camera&& other) noexcept
  {
    Camera tmp {};
    swap(*this, tmp);
    swap(*this, other);
    return *this;
  }

  friend void
  swap(Camera& first, Camera& second) noexcept
  {
    using std::swap;
    swap(first.device_, second.device_);
    swap(first.fd_, second.fd_);
  }

  void
  reopen()
  {
    this->close();
    this->open();
  }

  void
  open(const std::string& device = "")
  {
    if (this->fd_ >= 0)
      throw std::runtime_error {"camera already open"};
    if (!device.empty())
      this->device_ = device;
    if (this->device_.empty())
      throw std::runtime_error {"no associated device"};
    this->fd_ = camera_open(this->device_.c_str());
    if (this->fd_ < 0)
      throw std::runtime_error {"cannot open camera"};
  }

  void
  close()
  {
    if (this->fd_ >= 0)
      {
        if (camera_close(this->fd_) != 0)
          throw std::runtime_error {"cannot close camera"};
        this->fd_ = -1;
      }
  }
};

但是您首先确定这真的是一个好的设计决策吗?也许相机可以在必要时“重新加载”自己,而不用用这个实现细节来打扰用户?