<div dir="ltr">I think the main problem is that it's easy to use your class incorrectly. For example:<div><br></div><div>- What happens if your map is destructed? The SEXPs it is handling are effectively leaked.</div><div>- What if you copy your map? Since SEXPs are pointers, you now have two maps containing the same pointers, and if you were to attempt to remove a SEXP from both maps problems would occur.</div><div><br></div><div>Rather than attempting to manage the lifetime of these R objects in your map's methods, it's better to have wrapper classes that manage the lifetime of a single SEXP -- ie, what Rcpp does with its classes.</div><div><br></div><div>You might consider just using e.g. std::unordered_map<T, Rcpp::RObject> if you need to map some arbitrary types to R objects.</div><div><br></div><div>Best,<br>Kevin<br><div><br><div class="gmail_quote"><div dir="ltr">On Thu, Aug 16, 2018 at 1:11 AM Simon Dirmeier <<a href="mailto:simon.dirmeier@web.de">simon.dirmeier@web.de</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div text="#000000" bgcolor="#FFFFFF">
<p> </p>
<div class="m_2898377712113184403moz-text-html" lang="x-unicode">
<p>Dear all,</p>
I have a question about <i>R_PreserveObject </i>and<i>
R_ReleaseObject </i>and<i> </i>thought this would be good
place to post it.
<br>
I apologize if the question is not suitable or naive.<br>
<br>
Suppose I have something like the class below for which I use
Rcpp-modules to extend it to R (code not shown).<br>
I use "insert" to add key-value pair to a map and "remove" to
remove an entry. <br>
<br>
I am not having memory issues or so, but the solution seems wrong
to me and I am concerned that it causes problems.<br>
Could you please give me some advice if this implementation is
wrong or unefficient?<br>
<br>
Thank you in advance.<br>
Best,<br>
Simon<br>
<br>
<p><font face="Calibri">template<typename T><br>
class map<br>
{<br>
public:<br>
map() = default;<br>
<br>
size_t size()<br>
{<br>
return map_.size();<br>
}<br>
<br>
void insert(T& t, SEXP u)<br>
{<br>
SEXP s = Rf_duplicate(VECTOR_ELT(u, i));<br>
R_PreserveObject(s);<br>
<br>
map_.insert(std::pair<T, SEXP>(t[i], s));<br>
}<br>
<br>
void remove(T& t)<br>
{<br>
auto iter = map_.equal_range(t);<br>
for (auto it = iter.first; it != iter.second;
++it)<br>
{<br>
R_ReleaseObject(it->second);<br>
}<br>
map_.erase(t);<br>
}<br>
<br>
private:<br>
std::unordered_map<T, SEXP> map_;<br>
};</font><br>
</p>
<br>
<br>
</div>
</div>
_______________________________________________<br>
Rcpp-devel mailing list<br>
<a href="mailto:Rcpp-devel@lists.r-forge.r-project.org" target="_blank">Rcpp-devel@lists.r-forge.r-project.org</a><br>
<a href="https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel" rel="noreferrer" target="_blank">https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel</a></blockquote></div></div></div></div>