[C++-sig] operators and avoiding copying
Neal D. Becker
ndbecker2 at verizon.net
Tue Jul 13 20:29:35 CEST 2004
I want to learn how to implement operators (for arithmetic) while avoiding
copying large objects.
Let's say I have this:
template<typename T>
struct MyVec : public std::vector<T>, boost::addable<MyVec<T> > {
MyVec(){}
template<typename in_t>
MyVec (in_t in, in_t inend) : std::vector<T> (in, inend) {}
MyVec (size_t i) : std::vector<T> (i) {}
MyVec& operator+=(MyVec const& rhs) {
for (size_t i = 0; i < size(); i++)
(*this)[i] += rhs[i];
return *this;
}
};
typedef MyVec<double> DMyVec;
The reason for using MyVec rather than directly wrapping std::vector is to
derive from addable. This code seems to compile OK:
BOOST_PYTHON_MODULE(STL)
{
class_<DMyVec>("MVec")
.def(init<size_t>())
.def(init<const DMyVec&>())
.def("size", &DMyVec::size)
.def("resize", (void (DMyVec::*)(size_t, const
double&) )&DMyVec::resize)
.def("resize", (void (DMyVec::*)(size_t) )&DMyVec::resize)
.def(vector_indexing_suite<DMyVec>())
.def (self + other<DMyVec>())
.def (self += self)
;
Question is, does it make unnecessary copies of the vectors and if so, how
to avoid this? I'd assume that return value optimization is possible. Any
way to learn more? Staring at the code is not easy.
More information about the Cplusplus-sig
mailing list