问题
In armadillo, the advanced constructor provide the way to share memory like
mat B(10,10);
mat A(B.memptr(),2,50,false, true);
but in c++ program about class, one should first declare variables in head file,like
mat A,B;
and realize other things in cpp file.
So, anyone can tell me how to share memory between mat A and mat B in cpp file with the declaration of mat A and B in head file?
回答1:
You can declare the B
matrix as reference the A
matrix when declaring your class. For example:
class foo
{
public:
mat A;
mat& B; // alias of A
foo()
: B(A) // need to initialize the reference as part of the constructor
{
A.zeros(4,5);
A(1,1) = 1;
B(2,2) = 2;
A.print("A:");
B.print("B:");
}
};
Another (more brittle) solution is to use a common matrix, then assign the memory to other matrices using C++11 std::move(). For example:
#include <utility>
#include <armadillo>
using namespace std;
using namespace arma;
int main()
{
mat C(4,5, fill::zeros); // C is the common matrix
mat A:
mat B;
A = std::move( mat(C.memptr(), C.n_rows, C.n_cols, false, false) );
B = std::move( mat(C.memptr(), C.n_rows, C.n_cols, false, false) );
// note: in the above, the last argument of 'false' is important
A(1,1) = 1;
B(2,2) = 2;
// A and B will both have 1 and 2 as they're using the same memory
A.print("A:");
B.print("B:");
}
If you're using gcc or clang, you can enable C++11 mode with the -std=c++11
switch.
回答2:
In vs 2013,
#define ARMA_USE_CXX11
should be included. And then std::move would work.
Thanks hbrerkere for guiding right way.
来源:https://stackoverflow.com/questions/34896324/how-to-share-common-memory-in-armadillo