Problem with Particle.Variable (dynamic allocation?)

I’ve got some problem with cloud variables where the corresponding c++ variable is dynamically allocated. Here’s a simplefied version of my code:

class TestVarClass {
   TestVarClass(String s) {
   double _t;   
std::vector<TestVarClass> tt = {TestVarClass("test1"),TestVarClass("test2")};

test1 and test2 will quite random values (i e 4.342001538768913e-270)

Is it impossible to use dynamically allocated objects with the cloud variables?

I should perhaps clarify that if I create the object directly on the stack

TestClass t("test");

everything works as expected.

I believe this is not a class member variable problem, as this works:

TestVarClass vars[2] = {TestVarClass("test1"),TestVarClass("test2")};

I’m pretty sure this is a copy constructor problem. The std::vector makes a copy of the TestVarClass object when it adds it to the vector. The problem is that this implementation can’t be copied using the default copy constructor or operator, because Particle.variable will continue to point to the old spot in memory, which will then get freed, causing the weird values.


I believe @rickkas7 is correct here. Note too that std::vector can also call the copy constructor when it runs out of storage and needs to grow the vector–it basically allocates a bigger block and copy constructs all the current elements into it before adding the newest one during push_back.

When you call Particle.variable() are you registering a memory location as a cloud accessible variable, so it makes sense that the location of the variable in memory cannot change if you want the variable to continue to work.


After some sleep it seems so obvious… Thanks!

I’ll new the double in the constructor and store a pointer instead. The objects will live till the end of time so I dont have to free them.