Re: Problem with references
fdm wrote:
In a class I have the following functions:
template <typename PointType>
class ControlPoint
{
public:
typedef typename PointType::ValueType ValueType;
// Used for read only
PointType getDeformation() const {
return m_deformation;
}
// Used when updating m_deformation field
PointType & getDeformation(){
return m_deformation;
}
PointType m_deformation;
};
In some other code I run through a list of empty controlPoints and
initializes the m_deformation field:
int a = 0;
int params = m_ControlPoints.size(); // std::vector with controlpoints.
for (int i=0; i<NDimensions; i++) {
int ctrlCount = 0;
for (int j=a; j<params+a; j++) {
ControlPointType cp = m_ControlPoints[ctrlCount];
So, here you make a copy of the 'ctrlCount'th element of that vector.
cp.getDeformation()[i] = parameters[j];
And here you change the deformation *for that copy*. Do you expect the
vector element to change as well? Why?
It's the same as:
std::vector<int> v(3); // three zeros
int a = v[0]; // make a copy of the 0th element
a = 42; // change the copy
std::cout << "v[0] = " << v[0]; // what will it print?
What do you expect that code to change in the 'v' vector?
std::cout<< "cp.getDeformation() = " << cp.getDeformation() <<
std::endl;
ctrlCount++;
}
a = a + params;
}
The line:
std::cout<< "cp.getDeformation() = " << cp.getDeformation() <<
std::endl;
prints the expected result:
...
cp.getDeformation() = [1058, 0]
cp.getDeformation() = [1059, 0]
cp.getDeformation() = [1060, 0]
cp.getDeformation() = [1061, 0]
cp.getDeformation() = [1062, 0]
cp.getDeformation() = [1063, 0]
cp.getDeformation() = [0, 7000]
cp.getDeformation() = [0, 7001]
cp.getDeformation() = [0, 7002]
cp.getDeformation() = [0, 7003]
cp.getDeformation() = [0, 7004]
cp.getDeformation() = [0, 7005]
...
Just after this loop I create another loop that runs through the same
controlpoints and prints the m_deformation filed to verify that its
correct:
for (int i=0; i<params; i++) {
ControlPointType cp = m_ControlPoints[i];
std::cout << "cp.getDeformation() = " << cp.getDeformation() <<
std::cout;
}
but now they no longer exists:
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
cp.getDeformation() = [0, 0]
I have verified that the function:
// Used when updating m_deformation field
PointType & getDeformation(){
return m_deformation;
}
is called, but why are the m_deformation field 0 when I read it afterwards?
Because you never change them.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask