Search code examples
c++arduinosmart-pointersunique-ptrauto

Reassign variable of type auto that is currently std::unique_ptr


I am currently experimenting with the ESP32-CAM, which is a microcontroller with integrated camera that you can program through the Arduino IDE (with C++11). For capturing images with the cam, there is a library called 'esp32cam', which contains the function esp32cam::capture(). This function apparently returns a variable with the type std::unique_ptr<esp32cam::Frame>. There is also an example sketch, which saves the returned frame in a local variable of the type auto:

auto frame = esp32cam::capture();

For my project though, I want to store the last image captured by the cam globally, so I tried this:

auto lastPic = std::unique_ptr<esp32cam::Frame>();
void takePicture() {
  lastPic = esp32cam::capture();
}

However, that gave me the following error:

use of deleted function 'std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = esp32cam::Frame; _Dp = std::default_delete<esp32cam::Frame>]'

I am completely new to C++, so I do not really understand what this means, but as far as I am concerned std:unique_ptr manages an object and disposes of it when it does not need it anymore, and since I attempt to add a different object to the variable, it is basically a different unique_ptr and therefore a different type as well, so I cannot assign it. It could also very well be that I understood this entirely wrong though.

So my question is: How can I reassign this variable?

Any help is appreciated; thanks in advance.


Solution

  • Try changing this:

    auto lastPic = std::unique_ptr<esp32cam::Frame>();
    void takePicture() {
      lastPic = esp32cam::capture();
    }
    

    to this:

    auto lastPic = std::unique_ptr<esp32cam::Frame>();
    void takePicture() {
      lastPic = std::move (esp32cam::capture());
    //          ^^^^^^^^^
    }
    

    (Because std::unique_ptr is moveable but not copyable.)