简体   繁体   English

C ++中的可用内存(armadillo)

[英]Free memory in c++ (armadillo)

I want to free memory after using an object ('ii', in the following program) in c++: 我想在c ++中使用对象(以下程序中的“ ii”)后释放内存:

#include <iostream>
#include <armadillo>

using namespace std;
using namespace arma;

int main()
{
    cx_mat ii(2,2,fill::eye);
    cout << ii <<endl;
    free (ii);
    return 0;
}

But after compiling, I encounter to the following error: 但是编译后,我遇到以下错误:

error: cannot convert ‘arma::cx_mat {aka arma::Mat<std::complex<double> >}’ to ‘void*’ for argument ‘1’ to ‘void free(void*)’

can any body guide me? 有身体可以引导我吗?

cx_mat ii(2,2,fill::eye);

That's allocated on the stack, you can't free it, it will be destroyed when your program exits the scope. 那是在堆栈上分配的,您不能释放它,当程序退出作用域时,它将被销毁。

http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

You can only free pointers holding an address returned by malloc , calloc or realloc . 只能 free保存由malloccallocrealloc返回的地址的指针。 Nothing else. 没有其他的。 In particular, no matrices. 特别是没有矩阵。

You also should not need to use free in C++, ever. 您也永远不需要在C ++中使用free

In your case, you do not need to do anything to free the memory, the destructor of the matrix will take care of that. 在您的情况下,您无需执行任何操作来释放内存,矩阵的析构函数将负责处理此事。

The reason you're getting the error you're getting is because you're not passing a pointer to the function. 收到错误的原因是因为您没有传递指向该函数的指针。

However, free requires that you pass a pointer that has been returned by malloc , calloc , or realloc , otherwise undefined behavior occurs. 但是, free要求您传递malloccallocrealloc返回的指针,否则会发生未定义的行为。

The memory of your object will be freed when your function returns, or exits. 当函数返回或退出时,对象的内存将被释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM