Move Semantics and std::vector<>

So, I'm currently plodding along attempting to learn more of "Modern C++" -- using the STL, etc.

Please see the code below (compiling for Adafruit ESP32 Feather Huzzah). It defines a class that contains a dynamically allocated data member. An object of this class is instantiated and then a copy of the object is placed in a std:vector<> using Move Semantics.

The Serial port output is shown below the code and is exactly what I expected -- the object is first constructed and then a copy placed into the vector via the Move Constructor. Also, as expected, the Move Assignment Operator is not called at all.

Here's the question …. if I comment out the Move Assignment Operator, the code fails to compile with the error message attached (can't include inline --- exceeds character limit). So, why does the Move Assignment Operator need to be implemented if it's not even called?

Thanks.

Code:

#include "Arduino.h"

class MyClass {
  public:
    MyClass() : id(objectCounter++), data(new uint8_t[10]) {
      printf("Constructing: %d\n", id);
    }

    MyClass(MyClass &&source) : id(objectCounter++), data(source.data) {
      source.data = nullptr;
      printf("Move Constructing: %d From: %d\n", id, source.id);
    }

    ~MyClass() {
      delete[] data;
      printf("Destructing: %d\n", id);
    }

    MyClass &operator=(MyClass &&rhs) {      // <------ Must be present even though never called ?????
      delete[] data;
      data = rhs.data;
      rhs.data = nullptr;
      printf("Move Assigning: %d From: %d\n", id, rhs.id);
      return *this;
    }

    MyClass(const MyClass &source) = delete;
    MyClass &operator=(const MyClass &rhs) = delete;

  private:
    uint8_t id;
    uint8_t *data;
    static uint8_t objectCounter;
};

uint8_t MyClass::objectCounter = 0;

void setup() {
  std::vector<MyClass> vect;

  Serial.begin(115200);
  delay(1000);

  MyClass object0;
  vect.insert(vect.end(), std::move(object0));
}

void loop() {
}

Serial Port Output:

Constructing: 0
Move Constructing: 1 From: 0
Destructing: 0
Destructing: 1

ErrorMessage.txt (8.16 KB)

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.