B
barcaroller
Is it considered "acceptable" practice to return a const reference to
a private data member (something similar to string.c_str())?
class X
{
public:
const string& getString() const
{
return mystr;
}
private:
string mystr;
}
I know I'm breaking encapsulation but the other two options (below)
seem inefficient:
string getString() const
{
// copy constructor is invoked
return mystr;
}
... or ...
void getString(string& resString) const
{
// assignment operator is invoked
resString = mystr;
}
a private data member (something similar to string.c_str())?
class X
{
public:
const string& getString() const
{
return mystr;
}
private:
string mystr;
}
I know I'm breaking encapsulation but the other two options (below)
seem inefficient:
string getString() const
{
// copy constructor is invoked
return mystr;
}
... or ...
void getString(string& resString) const
{
// assignment operator is invoked
resString = mystr;
}