gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:55 24 4
gpt4 key购买 nike

我有一个名为 Camera 的类,它在构造函数中使用 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

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

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;
}
}
};

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

关于c++ - 当对象表示硬件组件时,我应该使用指向对象还是对象的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com