I'm having trouble inventing a good memory management strategy for Constraint objects.
My goals:
* python-powered lifetime management
(i.e., no storage on stack)
* universal copy() method - I don't want to repeat it for every constraint
* constructable from Base::Type
So the base class:
Code: Select all
class Constraint: public BaseClass
{
protected://data
... //some members
PyObject* _twin; // <- points to ConstraintPy object, which is responsible for deleting Constraint instance
public:
virtual HConstraint copy() const;
... getPyObject();
}
The savior seems to be the default assignment operator, which I could use from copy() to do all the copying, and then manually reset _twin to the new twin.
I have tested:
Code: Select all
// Example program
#include <iostream>
class A
{
public:
int mmA = 0;
};
class B: public A
{
public:
int mmB = 0;
B(int mma, int mmb){
mmA = mma;
mmB = mmb;
}
};
int main()
{
A* inst1 = new B(1,1);
A* inst2 = new B(2,2);
*inst1 = *inst2;
std::cout << "inst1 " << inst1->mmA <<" " << static_cast<B*>(inst2)->mmB;
delete inst1;
delete inst2;
}
Now the next problem, I'd like to protect that assignment. So that no one uses it to make a copy of _twin pointer, which then points to the wrong object. Which I failed to:
Code: Select all
// Example program
#include <iostream>
class A
{
public:
int mmA = 0;
protected:
virtual A& operator=(A& other) = default; // <-protected assignment
};
class B: public A
{
public:
int mmB = 0;
B(int mma, int mmb){
mmA = mma;
mmB = mmb;
}
};
int main()
{
A* inst1 = new B(1,1);
A* inst2 = new B(2,2);
*static_cast<B*>(inst1) = *static_cast<B*>(inst2); // <- unfortunately, still works =(
delete inst1;
delete inst2;
}
For example, if I override assignment with actual code, is there any way to use the default assignment somehow?