C++ constness and reference
Case 1: Make function const vs. non-const
const Track& ScoreTableElement::getTrackLeft() const{
return left_;
}
vs.
const Track& ScoreTableElement::getTrackLeft()
{
return left_;
}
The difference is, if the function is not marked const, then we can not call this function on a const variable or const reference variable, because this function could change the content of the object,
so the const variable/reference will not allow the calling of this function.
Example:
sf::of::ScoreTableElement element(track_left, track_right, 4.5F);
scoretable.push_back(element);
const sf::of::ScoreTableElement element_out = scoretable.back();
// or const sf::of::ScoreTableElement & element_out = scoretable.back();
element_out.getTrackLeft(); // compiler error getTrackLeft() is not const function
Case 2: Assign return const reference to const vs. non-const reference
const Track& ScoreTableElement::getTrackLeft() const
{
return left_;
}
sf::of::Track &track = element_out.getTrackLeft(); // non-const ref, not possible, can
//not assign const to non-const reference
vs.
const sf::of::Track &track = element_out.getTrackLeft(); // const reference
Case 3: Assign returned const reference to reference or variable
const Track& ScoreTableElement::getTrackLeft() const
{
return left_;
}
const sf::of::Track track = element_out.getTrackLeft(); // assign to variable
or
const sf::of::Track &track = element_out.getTrackLeft(); // assign to reference
When assign a returned reference to non-reference variable, what happened is calling the assignment operator for the reference object. The default assignment operator will first call the destructor(maybe default one) to un-initialize the object bundled with left-hand-side variable, and then call the copy constructor(maybe the default one) to take the reference object as input, this will cause the a new object to be created, and the members of the new objects get initialized use the members from the reference object.
Important thing is, the newly created object contained in the variable is not the
same as the referenced object.
Case 4: Return const ref or non-const ref
Track& ScoreTableElement::getTrackLeft() const
{
return left_;
}
or
const Track& ScoreTableElement::getTrackLeft() const
{
return left_;
}
See case 2 and case 3, if we return a const reference, then it must be assigned to a const reference/variable, a non-const reference/variable can not take it.
This means no matter you have a new object(via assign to variable) or the old one(via reference), you can not change the content of the object.
评论
发表评论