I found some (to me) unexpected behavior when initializing arrays with smart pointers. This minimal example compiles without issue:
#include <memory>
void setup()
{
std::shared_ptr<char[]> var(new char[10]);
}
void loop()
{
;
}
Replacing std::unique_ptr<char[]> with std::shared_ptr<char[]> gives a compiler error
cannot convert 'char*' to 'char (*)[]' in initialization
Why the difference?
Side question: Is a custom deleter for arrays necessary in the Arduino IDE (pre- C++17)?
Any insights are appreciated!
This section looks like it might be applicable:
std::shared_ptr<T>::shared_ptr - cppreference.com.
That seems to work when compiled for a Teensy 3.2:
#include "Arduino.h"
#include <memory>
class FOO {
public:
FOO() : instance(instanceCount++) {
Serial.printf("Constructing Instance %d\n", instance);
}
~FOO() {
Serial.printf("Destructing Instance %d\n", instance);
}
private:
uint8_t instance;
static uint8_t instanceCount;
};
uint8_t FOO::instanceCount = 0;
void setup() {
delay(1000);
Serial.printf("Creating\n\n");
std::unique_ptr<FOO[]> arr(new FOO[10]);
Serial.printf("\nMoving\n");
std::shared_ptr<FOO> var(std::move(arr));
auto ptr = var.get();
Serial.printf("\nPointer = 0x%08X\n", uint32_t(ptr));
Serial.printf("\nReleasing\n\n");
var.reset();
Serial.printf("\nReleased\n");
ptr = var.get();
Serial.printf("\nPointer = 0x%08X\n", uint32_t(ptr));
}
void loop() {
}
Result:
Creating
Constructing Instance 0
Constructing Instance 1
Constructing Instance 2
Constructing Instance 3
Constructing Instance 4
Constructing Instance 5
Constructing Instance 6
Constructing Instance 7
Constructing Instance 8
Constructing Instance 9
Moving
Pointer = 0x1FFF9328
Releasing
Destructing Instance 9
Destructing Instance 8
Destructing Instance 7
Destructing Instance 6
Destructing Instance 5
Destructing Instance 4
Destructing Instance 3
Destructing Instance 2
Destructing Instance 1
Destructing Instance 0
Released
Pointer = 0x00000000
Thanks for the anwser! I also tried to compile this code
#include <memory>
#include <stdio.h>
int main()
{
auto var = std::shared_ptr<int[]>(new int[10]);
printf("Test");
return 0;
}
on onlinegdb.com with C++14 and C++17 - compiles without issue.
The error occured in the Arduino IDE 1.8.13 with the ESP32 Dev Module board - perhaps a bug there?