[Rcpp-devel] Understanding the behaviour of const CharacterVector as a function parameter
Simon Zehnder
szehnder at uni-bonn.de
Sun Sep 29 20:20:54 CEST 2013
On Sep 29, 2013, at 3:24 PM, Romain Francois <romain at r-enthusiasts.com> wrote:
> Le 29/09/13 14:06, Simon Zehnder a écrit :
>> Dear Rcpp::Users and Rcpp::Devels,
>>
>> I would like to understand a certain behaviour of my code I encountered lately.
>>
>> I am working with CharacterVector and the following behaviour occurred:
>>
>> void test1 (Rcpp::CharacterVector &charv)
>> {
>> Rprintf("test1: %s\n", (char*) charv(0));
>> }
>>
>> void test2 (const Rcpp::CharacterVector &str)
>> {
>> Rprintf("test2: %s\n", (char*) charv(0));
>> }
>
> Try actually using the variable you pass in, as in:
>
> void test2 (const Rcpp::CharacterVector &str)
> {
> Rprintf("test2: %s\n", (char*) str(0));
> }
My fault! :)
I tried to post a simpler example than my code and made this silly error.
> Although it still exposes the bug.
>
> You can use something like this in the meantime:
>
> void test2 (const Rcpp::CharacterVector& charv)
> {
> String x = charv[0] ;
> Rprintf("test2: %s\n", x.get_cstring());
> }
>
This was my first approach. I write a date parser that converts strings to seconds since 1970 for Rcpp. Then I decided to convert my code to use char pointers, which I assumed to be much faster. It works with nonconst parameters and is indeed on 10e+6 values 1 second faster (takes 0.836 secs in total). Regarding the better performance of my code in case of using char I want to stick to it and accept here using nonconst parameters.
> It looks like the bug is about converting the result of charv(0) to a char*. Probably worth looking at the string_proxy class.
>
I took a look at the string_proxy class and other related classes. It takes some more time for me to understand what is going on, but step by step I get a better insight, what is going on under the hood.
Thank you for the quick response.
Best
Simon
> Romain
>
>> Using a string like "2013-05-04 20:23:21" for the Rcpp::CharacterVector gives the following outputs:
>>
>> test1: 2013-05-04 20:23:21
>>
>> test2: `
>>
>> This does also not change if I use a cast to const char* in test2. I tried something similar with strings and printing the c_str() of them, there the 'const' keyword does not make a difference - it always prints the correct string.
>>
>> Is this something specific to the Rcpp::CharacterVector, that uses a string_proxy for its elements returned by the operator ()? Is there a way to use const Rcpp::CharacterVector and get the behaviour of test1?
>>
>>
>> Best
>>
>> Simon
>
> --
> Romain Francois
> Professional R Enthusiast
> +33(0) 6 28 91 30 30
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
More information about the Rcpp-devel
mailing list