typedef std::vector <std::vector <int>> DataType;
class MyClass
{
public:
const DataType &getData() const;
DataType getData2() const;
private:
DataType data;
};
const DataType &MyClass::getData1() const
{
return data;
}
DataType MyClass::getData2() const
{
return data;
}
Should I avoid copying it by using getData1()? Is there any performance benefit to prefer const reference instead of getData2()? How should I return such "large" private member from class?
The difference is in what the users can do with your DataType
:
getData1
they can call only member functions marked const
, and access member variables as if they were declared constant, and only during the lifetime of the object that returned the reference.getData2
users can call any methods they wish, and make modifications as needed.The price for using getData2
is copying: if DataType
has an expensive copy constructor, the calls may become significantly more expensive.
You could improve upon this by implementing a copy-on-write strategy, and sharing data with reference counting. Of course, users will be able to make copies manually by calling the copy constructor on the constant reference:
DataType dtCopy(obj.getData1());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With