如何用"new"和"delete"替换"malloc"和"free"? [英] How to replace 'malloc' and 'free' with 'new' and 'delete'?

查看:174
本文介绍了如何用"new"和"delete"替换"malloc"和"free"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改以下代码,以便可以使用newdelete代替mallocfree?

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:请注意,我必须使用一个以float**作为参数的函数(不是我自己编写的),并且除了使用float**外,我别无选择(例如vector).

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:该函数来自邻近查询包(PQP),其编写方式如下:

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))变为new T.
  • T* b = (T*)malloc(N * sizeof(T))变为new T[N].
  • free(a)变为delete a.
  • free(b)变为delete[] b.
    • T* a = (T*)malloc(sizeof(T)) becomes new T.
    • T* b = (T*)malloc(N * sizeof(T)) becomes new T[N].
    • free(a) becomes delete a.
    • free(b) becomes delete[] b.
    • 所以您得到:

      myclass::myclass()
      {
        // first allocate rows (for pointers)
        m_R = new float*[3];
        // next allocate columns for float values
        for(int i=0;i<3;i++)
          *(m_R+i) = new float[3];
      }
      
      myclass::~myclass()
      {
        // first free memory allocated by columns
        for(int i = 0; i < 3; i++)
        {
          delete[] m_R[i];
        }
        // next free memory allocated by rows
        delete [] m_R;
      }
      

      请注意,这实际上不是非常理想.如果要使用3x3矩阵,最好在一个块中分配9个浮点数.

      Note that this is actually not very optimal. If you want 3x3 matrices, you're better off allocating 9 floats in one block.

      还请注意,您的C不正确.

      Also note that your C is incorrect.

      m_R = (float**)malloc(3*sizeof(float));
      

      应该是

      m_R = (float**)malloc(3*sizeof(float*));
      

      您的代码可能起作用",因为您正在编译32位,其中floatfloat*是4个字节.在64位版本中,float*是8个字节.

      Your code probably "works" because you're compiling for 32-bit, where float and float* 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:

      class myclass{
        private:
          float m_R[3][3];
        public:
          myclass() {}
          ~myclass() {}
          void setR(void);
          float* operator[](unsigned i) { return m_R[i]; }
          const float* operator[](unsigned i) const { return m_R[i]; }
      };
      
      void myclass::setR(void)
      {
        for(int i=0;i<3;i++)
        {
          for(int j=0;j<3;j++)
          {
            (*this)[i][j] = 10*i+j;
            //cout << (*this)[i][j] << ", ";
          }
          //cout << "\n";
        }
      }
      
      int main () {
      
        myclass obj;
        obj.setR();
      
        for(int i=0;i<3;i++)
        {
          for(int j=0;j<3;j++)
          {
            printf("%02d, ",(int)(obj[i][j]));
          }
          cout << "\n";
        }
      
        return 0;
      }
      

      这是我通常的操作方式,因此我可以利用对象内存储的效率来获得[] []的可读性.

      This is how I usually do it, so I get the readability of [][] with the efficiency of in-object storage.

      这篇关于如何用"new"和"delete"替换"malloc"和"free"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆