No, the use of new
and delete
is not warranted here. If your camera “becomes bad” and you wish to dispose of it in favor of a new one, simply assign a new one.
const std::string device {"/dev/cameras/front"}; // whatever
Camera camera {device};
// do something...
if (camera.bad())
camera = Camera {device}; // replace by a new one
You'll probably want to overload the assignment operator of your Camera
class for this to work. Since the Camera
class is resource-owning, it should not be copyable but movable. I don't know how you are talking to the hardware so I've made the following example a bit up but it should give you the correct idea how to implement your type.
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;
}
}
};
But are you sure that this is really a good design decision in the first place? Maybe the camera can just “reload” itself when necessary and not bother the user at all with this implementation detail?