SSi*_*ilk 2 c++ scope function new-operator
这是一个漫长的过程.我有一个从磁盘加载一些图像数据的功能.我用三种不同的方法尝试过这种方法,其中一种方法不起作用,我想知道最聪明的方法是什么.
方法1:
我曾经设置它,以便加载的数据是函数的参数,这似乎需要在函数外部为它分配空间,然后将指针传递给分配的空间.这需要提前知道图像的大小,因此必须首先获得辅助函数以获得图像的宽度和高度.以下是一个例子.
优点:在调用代码中更明确地分配内存,因此应该删除.
缺点:需要提前知道图像大小.
// Data allocated outside the image, allocated space passed to function. This works.
// Notice that width & height are passed to the function.
size=(*width)*(*height);
image = new unsigned char[size];
void read_pgm(unsigned char *image, char *file_name, int width, int height){
// Code to read sizeof(char)*width*height bytes of data from the file into image
}
Run Code Online (Sandbox Code Playgroud)
方法2:
我认为让函数分配自己的数据会很好,所以我不需要传递它的大小.如果我试图在函数中为它分配空间,它在函数结束后似乎丢失了.在下面的例子中,函数read_pgm运行正常,但如果我然后尝试将该数据写入另一个文件,我的代码崩溃.
优点:不需要提前知道图像大小,不需要在调用代码中分配数据.
缺点:不起作用.另外,如果确实如此,如果我没有在函数外部清除图像,那么在循环中反复调用会导致内存泄漏吗?
// Data allocated inside the image for a pointer passed to the function. This doesn't work.
void read_pgm(unsigned char *image, char *file_name, int *width, int *height){
size=(*width)*(*height);
image = new unsigned char[size];
// Code to read the data from the file into image
}
Run Code Online (Sandbox Code Playgroud)
方法3:
这里,数据再次在函数中分配,但作为返回项目返回.这是有效的,即我可以将数据写入另一个图像.我不明白为什么这样做而方法2没有.
优点:与方法2相同.
缺点:与方法2相同,但目前无效.
// Data allocated in the function, and returned. This works.
unsigned char* read_pgm(char *file_name, int *width, int *height){
// Allocate data for the image
size=(*width)*(*height);
image = new unsigned char[size];
// Code to read the data from the file into image
return image; // Return pointer to the data
}
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是:
在这种情况下,将功能设置为自己分配空间是否更智能,因此调用代码不需要提供图像大小?或者在函数外部分配更聪明,提醒您需要在某个时刻在图像上调用删除.或者我错误地认为需要这样做?似乎在循环中调用方法2或方法3会导致内存泄漏.
为什么方法2不起作用?
谢谢.
如果你想知道聪明的方式,那么答案必须是"以上都不是".聪明的方式?使用矢量.这就是它的用途.因为new直接使用很糟糕.管理自己内存的界限很糟糕.我们有课程.而char*对于字符串?至少让它成为一个const char*.const std::string&更好.我还要问 - 你试图读取的图像格式是什么,不能以文件格式存储图像的宽度和高度?在我看来,你最好从文件中读取它.
std::vector<unsigned int> void ReadImage(const std::string& filename, int width, int height) {
std::vector<unsigned int> imageData(width * height);
// Read here from filestream
}
std::vector<unsigned int> imageData = ReadImage("ohai.png", 1000, 600);
Run Code Online (Sandbox Code Playgroud)
您需要了解 - const正确性,RAII和标准库.