[c++] 内存管理

2017-09-22  本文已影响0人  ericdejavu

created by Dejavu


介绍

c++在构造过程中经常会遇到内存管理的问题,这里我讲解一些我在写kinect驱动时遇到的一些主要的内存和数据管理问题


栈中创建导致溢出
堆中创建

示例源码

class DataSet{
public:
   cv::Mat color;
   cv::Mat depth;
   cv::Point3f *worldPt;
   std::vector<cv::KeyPoint> kp;
   cv::Mat im;
   DataSet() : worldPt(new cv::Point3f[ROWS*COLS]) {}
   ~DataSet() { delete [] worldPt; }
   void set(DataSet dataSet);
   void operator=(DataSet &dataSet);
};

//本例需要查看的函数
void DataSet::set(DataSet dataSet) {
   color = dataSet.color.clone();
   depth = dataSet.depth.clone();
   memmove(worldPt,dataSet.worldPt,sizeof(cv::Point3f)*COLS*ROWS);
   im = dataSet.im.clone();
   for(int i=0;i<kp.size();i++) kp.push_back(dataSet.kp[i]);
}
void DataSet::operator=(DataSet &dataSet) {
   color = dataSet.color.clone();
   depth = dataSet.depth.clone();
   memmove(worldPt,dataSet.worldPt,sizeof(cv::Point3f)*COLS*ROWS);
   im = dataSet.im.clone();
   for(int i=0;i<kp.size();i++) kp.push_back(dataSet.kp[i]);
}
class DataStream : public DataSet {
private:
    Freenect::Freenect freenect;
    bool isSelect,isShowInfo,isCopyOperation;
    MyFreenectDevice& device;
    bool getData();
    static void* getPthreadImg(void*);
    void run_thread();

public:
    Mutex imgLock;
    bool isSignalLoss;
    bool isCalcFeature;
    std::vector<VisImg> visImg;

    DataStream() : device(freenect.createDevice<MyFreenectDevice>(0)) {
        device.startVideo();
        device.startDepth();
        run_thread();
    }
    ~DataStream() {
        device.stopVideo();
        device.stopDepth();
    }

    bool calc_feature();
    DataSet copy();
    cv::Mat clone();
    cv::Point3f depth_to_world(int camerax,int cameray,int depthData);
    int add(cv::Mat &src,std::string name);
};

//本例需要查看的函数
DataSet DataStream::copy() {
    isCopyOperation = true;
    Mutex::ScopedLock lock(imgLock);
    DataSet dataSet;
    dataSet.color = color.clone();
    dataSet.depth = depth.clone();
    for(int i=0;i<ROWS*COLS;i++) dataSet.worldPt[i] = worldPt[i];
    if(isCalcFeature) {
        dataSet.im = im.clone();
        for(int i=0;i<kp.size();i++) dataSet.kp.push_back(kp[i]);
    }
    isCopyOperation = false;
    return dataSet;
}
上一篇 下一篇

猜你喜欢

热点阅读