C++智能指针,实现Mat类的复制控制

定义智能指针的通用技术是采用一个使用计数器。智能指针类将一个计数器与类指向的对象相关联。使用计数跟踪该类有多少个对象共享同一指针。当计数器为0时删除对象。使用计数有时也称为引用计数

//利用一个引用计数器控制复制和赋值构造函数,当引用计数器为零时,可以数据
//My_Image.h
#pragma once
#include 
namespace My_Code{
class Image_Data{
friend class My_Image;
Image_Data(const int& r, const int& m,  int** src);
~Image_Data();

int** data;
int rows;
int cols;
int use;                      //应用计数器
};

class My_Image
{
public:
~My_Image(void);
My_Image(const My_Image& src);
My_Image(int r, int c, int ** data);
My_Image& operator=(const My_Image& src);

My_Image& copyto(My_Image& src);
friend std::ostream&  operator<<(std::ostream &os, const My_Image& src);

private:
int get_rows() const { return image->rows;}
int get_cols() const { return image->cols;}
int** get_data() const{ return image->data;}
Image_Data* image;
};
}

//My_Image.cpp
#include "My_Image.h"
#include 

using namespace std;

namespace My_Code{
Image_Data::Image_Data(const int& r, const int& c,  int** src)
{
data = new int*[r];
for(int i=0; inew int[c];
for(int i=0; ifor(int j=0; j1;
}

Image_Data::~Image_Data()
{
for(int i=0; idelete[] data[i];
delete[] data;
cout<<"destruct called"<int r, int c, int ** data):image(new Image_Data(r, c, data)){ }

My_Image::My_Image(const My_Image& src){
image = src.image;
image->use++;
}

My_Image& My_Image::operator=(const My_Image& src)
{
if(--image->use ==0)
delete image;
image = src.image;
image->use++;
return *this;
}

ostream& operator<<(ostream &os, const My_Image& src){
for(int i=0; ifor(int j=0; j" ";
os<return os;
}

//可以将一个图像的数据拷贝给另一个图像
My_Image& My_Image::copyto(My_Image& src)
{
if(--src.image->use==0)
delete src.image;
src.image = new Image_Data(get_rows(), get_cols(), image->data);
return src;

}

My_Image::~My_Image(void)
{
if(--image->use == 0)
delete image;
}
}

//main.cpp
#include 
#include 
#include "My_Image.h"

using namespace std;
using namespace My_Code;

void main (void)
{ 
//生成一个int** 类型,作为二维数组参数
int ** data = new int*[2];
data[0] = new int[2*3];
for(int i=1; i<3; i++)
data[i] = data[i-1] + 2;


for(int i=0; i<2; i++)
for(int j=0; j<3; j++)
data[i][j] = i+j;

My_Image image1(2, 3, data);
My_Image * image2 = new My_Image(image1);
cout<<*image2;

for(int i=0; i<2; i++)
for(int j=0; j<3; j++)
data[i][j] = (i+j)*2;

My_Image  image3(2, 3, data);
image3.copyto(image1);

cout << image1 ;

system("pause");
}

C++智能指针,实现Mat类的复制控制_第1张图片

你可能感兴趣的:(opencv)