valarray assignment question

P

Prune Tracy

I have a question about assignment of slices of valarrays. I want to
assign one general slice of a valarray to another. It seems the only
way is to use the static_cast syntax, but this seems to involve
needless copies.

Example code follows:

#include <iostream>
#include <valarray>

// Simple class to see what copying is occurring.
class Cl {
public:
Cl() { std::cout << "Cl()" << std::endl; }
Cl(const Cl&) { std::cout << "Cl(const Cl&)" << std::endl; }
Cl& operator=(const Cl&) { std::cout << "operator=(const Cl&)" <<
std::endl; return *this; }
};

int main() {
std::valarray<Cl> u(4);
std::cout << "---" << std::endl;

std::valarray<Cl> v(4);
std::cout << "---" << std::endl;

std::gslice g(0, std::valarray<size_t>(2, 1),
std::valarray<size_t>(2, 1));
u[g] = static_cast<std::valarray<Cl> >(v[g]);
}

The output is:

Cl()
Cl()
Cl()
Cl()
---
Cl()
Cl()
Cl()
Cl()
---
operator=(const Cl&)
operator=(const Cl&)
operator=(const Cl&)
operator=(const Cl&)

i.e., there are 4 assignments instead of only 2. This is when using
-O3 optimisation on my compiler. Is there some way to avoid these
extra assignments?

Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top