6

I get this error when i try to compile my code: non-static reference member ‘Timestep& Timestep::previousTimestep’, can’t use default assignment operator

I create one Problem which creates a Timestep a reference to the this Timestepshould be stored in the vector solution. Besides i want to store a reference to a previous Timestep - and for the first Timestep that would be a reference to itself...

I read that i need to define an own operator if i have const members in a class what i try to set equal. However, removed all const elements form the code and it still don't work. Any suggestions? Thanks a lot.

class Problem {
public:
    void initialTimestep(arma::vec ic);
private:
    std::vector<Timestep> solution;
};

void Problem::initialTimestep(vec ic){
    Timestep myFirstTimestep(starttime, ic, nodes);
    solution.push_back(myFirstTimestep);
}



class Timestep {
public:
    Timestep(double starttime, arma::vec initialCondition, arma::vec nodelist);
private:
    Timestep& previousTimestep; //const
};

Timestep::Timestep(double starttime, vec initialCondition, vec nodelist)
: previousTimestep(*this)
    {
    //do stuff
}


int main() {
    int k = 3; //subdomains
    vec v = linspace(0., 1., k+1); //node spacing
    vec ic= ones<vec>(k+1); //initialconditions
    Problem myProblem(v, ic, 0., 1., 0.1);
    return 0;
}
dani
  • 3,677
  • 4
  • 26
  • 60

2 Answers2

6

No default assignment operator was created for your class Timestep because it contains a reference (which cannot be set later. it basically is a constant pointer to non-const data). solution.push_back(myFirstTimestep) requires the asignment though (or move with c++11) so you will have to define your own assignment (or move) operator (which of course you will not be able to do unless you change Timestep& previousTimestep to Timestep *previousTimestep in which case the default assignment will work as well).

example
  • 3,349
  • 1
  • 20
  • 29
  • 1
    Thank you for your answers. The comment about using `move` helped. In the end I use this `solution.emplace_back(starttime, ic, nodes)` to solve my problem (needs C++11). Seems like it is also the preferred way form a performance point of view. Besides it also resolves problems with const elements. – dani Mar 16 '14 at 19:06
4

You need to write your own assignment operator for the Timestep class (operator=).

Alternatively, you can use a Timestep pointer instead of a reference inside the Timestep class. That'd be my personal preference in this case. The compiler imposes a lot fewer rules about pointers, for various reasons.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62