How can I change the following code such that I can use new and delete instead of malloc and free?
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
class myclass{
private:
float **m_R;
public:
myclass();
~myclass();
float **getR(void);
void setR(void);
};
myclass::myclass()
{
// first allocate rows (for pointers)
m_R = (float**)malloc(3*sizeof(float));
// next allocate columns for float values
for(int i=0;i<3;i++)
*(m_R+i) = (float*)malloc(3*sizeof(float));
}
myclass::~myclass()
{
// first free memory allocated by columns
for(int i = 0; i < 3; i++)
{
free(m_R[i]);
}
// next free memory allocated by rows
free(m_R);
}
void myclass::setR(void)
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
m_R[i][j] = 10*i+j;
//cout << m_R[i][j] << ", ";
}
//cout << "\n";
}
}
float **myclass::getR(void)
{
return m_R;
}
int main () {
myclass obj;
obj.setR();
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%02d, ",(int)obj.getR()[i][j]);
}
cout << "\n";
}
return 0;
}
Edit1: Please note that I have to use a function (not written by me) which takes float** as argument and I have no choice (such as vector) than using float**.
Edit2: The function is from Proximity Query Package (PQP) written as following:
int
PQP_Distance(PQP_DistanceResult *result,
PQP_REAL R1[3][3], PQP_REAL T1[3], PQP_Model *o1,
PQP_REAL R2[3][3], PQP_REAL T2[3], PQP_Model *o2,
PQP_REAL rel_err, PQP_REAL abs_err,
int qsize = 2);
T* a = (T*)malloc(sizeof(T))becomesnew T.T* b = (T*)malloc(N * sizeof(T))becomesnew T[N].free(a)becomesdelete a.free(b)becomesdelete[] b.So you get:
Note that this is actually not very optimal. If you want 3×3 matrices, you’re better off allocating 9 floats in one block.
Also note that your C is incorrect.
should be
Your code probably “works” because you’re compiling for 32-bit, where
floatandfloat*are 4 bytes. On a 64 bit build,float*is 8 bytes.Honestly, though, since your dimensions are fixed and small, you should store everything in the object itself:
This is how I usually do it, so I get the readability of [][] with the efficiency of in-object storage.