[Rcpp-devel] use of auxiliary functions

Davor Cubranic cubranic at stat.ubc.ca
Tue Aug 10 01:38:45 CEST 2010


On 2010-08-07, at 7:03 PM, baptiste auguie wrote:

> Thanks Davor, Douglas and Dirk –– all your comments have been very
> helpful and I used them to improve my code (along with getting a
> better understanding of C++). The only thing I haven't tried yet is
> avoid duplicating the objects in memory using const (seems tricky from
> what I read on the net).

Using 'const' won't save you from duplicating objects: all it does is mark a variable/parameter as a constant, so that you can't accidentally change it. What does save you from duplication is passing arguments by reference. And passing arguments by reference is often combined with marking them 'const' for safety, because accidentally changing them would introduce wide-ranging bugs into your code that could be difficult to find.

Also, note that passing by const reference only saves space for complex objects, not primitive types like doubles and consts. So for the 'euler' function you used in your example, it would be recommended to make its signature:

arma::mat euler(const double phi, const double theta, const double psi);
In other words, 'phi', 'theta', and 'psi' are doubles, which I'm passing as constants.

While something like matrix multiply could be:

arma::mat mul(const arma::mat& a, const arma::mat& b);
Here, 'a' and 'b' are matrix objects, which I'm passing by constant reference.

Hope this helps.

Davor



More information about the Rcpp-devel mailing list