I have a class which basically is a text manager. It can draw text and whatnot. I basically want the color and text std::string to only be a constant reference. Would it then be alright to do
class TextManager {
const std::string &text;
void draw(const std::string &text) const;
public:
TextManager(const std::string &text)
{
this->text = text;
}
void someMethod()
{
draw(text);
}
};
I want when the class that owns an instance of TextManager’s text changes, the change is reflected in the TextManager.
would I be better off using a pointer?
thanks
This code doesn’t compile.
this->text = textdoesn’t do what you think it does – it’s not like Java where assigning a reference is like changing the pointer.reference = valuewill actually invoke the copy operator, so it will copy the value of the rhs to the lhs, either as member-by-member copy or using theoperator=if it was overridden. Since yourtextis const, you can’t do that.So in this case, you have to use a pointer – references cannot be modified once initialized.
EDIT: Just to explain ways in which you could use a reference:
const std::string &text = yourString;or:
That way, you have a permanent reference to whatever string you have.