[Rcpp-devel] Creating a std::vector of objects with const members

Douglas Bates bates at stat.wisc.edu
Thu Oct 6 21:57:46 CEST 2011


This may be more of a C++ question than strictly an Rcpp question, in
which case I guess I should finally get a stackoverflow.com login.

I have a collection of objects that each consist of a NumericVector
and a NumericMatrix.  The collection is called a population protocol
and the individual objects are called elementary protocols.

It is not a big deal in this case but I am wondering how to define the
population protocol using something like std::vector so that
elementary protocols can be added or removed but each elementary
protocol is read-only.

I have classes like

class ElemProt {
protected:
    const NumericVector d_vec;
    const NumericMatrix  d_mat;
public:
     ElemProt(const NumericVector&, const NumericMatrix&);
     const NumericVector& vec() const {return d_vec;}
     const NumericMatrix& mat() const {return d_mat;}
};

class PopProt {
protected:
     std::vector<ElemProt> d_prots;
     ...
public:
     PopProt(List);
}

In the constructor for PopProt the argument is a list of lists where
each of the inner lists contains a vector and a matrix.

What I want to do is to iterate over the elements of the list,
generating and inserting ElemProt objects into the d_prots member of
PopProt.  I haven't worked out an expression that preserves the const
nature of the members of the ElemProt instances while inserting or
deleting them from the d_prots member.  I have tried the usual
suspects like declaring the vector as std::vector<const ElemProt> but
that doesn't seem to work in the push_back method for the vector.

I suppose I could use a const cast but that always seems like cheating
(and, in a sense, it is).

Any suggestions?

I can flesh this out if anyone wants more detail.

P.S. The reason for wanting the NumericVector and NumericMatrix to be
const elements of the ElemProt class is because the constructors for
the NumericVector and NumericMatrix classes that take an SEXP do not
copy the contents but just use a pointer to the R object's contents.
Thus you want to protect that storage from being modified in the C++
code.


More information about the Rcpp-devel mailing list