@@ -1013,6 +1013,45 @@ bar$handleFoo(foo)
10131013#> Got a Foo!
10141014```
10151015
1016+ ### Returning objects of exposed classes
1017+
1018+ With ` RCPP_EXPOSED_WRAP ` (or ` RCPP_EXPOSED_CLASS ` ), functions and
1019+ methods can also return objects of a class exposed by a module. How
1020+ the object is passed to \proglang{R} depends on the return type:
1021+
1022+ - An object returned by value or by reference is _ copied_ , using the
1023+ copy constructor of the class, and the \proglang{R} object owns the
1024+ copy.
1025+ - A pointer is not copied: the \proglang{R} object takes _ ownership_
1026+ of the object it points to, and deletes it when the \proglang{R}
1027+ object is garbage collected. This is what a function returning a
1028+ newly allocated object needs, like the factories shown above, but
1029+ it means that a pointer may only be returned when nothing else owns
1030+ or deletes the object it points to. Returning ` this ` (e.g. to chain
1031+ method calls), a pointer to a data member or to an element of a
1032+ container, or the same pointer from more than one call results in the
1033+ object being deleted more than once, which typically crashes
1034+ \proglang{R} during garbage collection.
1035+
1036+ ``` {Rcpp ownership, eval=FALSE}
1037+ class Counter {
1038+ public:
1039+ Counter() : n(0) {}
1040+
1041+ // fine: R owns, and eventually deletes, the new Counter
1042+ static Counter* create() { return new Counter; }
1043+
1044+ // wrong: the R object returned by inc() would delete *this
1045+ // a second time
1046+ Counter* inc() { n++; return this; }
1047+
1048+ // fine: return void, or a copy, and chain the calls in R
1049+ void increment() { n++; }
1050+
1051+ int n;
1052+ };
1053+ ```
1054+
10161055### Full example
10171056
10181057<!-- TODO: maybe replace this by something from wls or RcppModels ? -->
0 commit comments