Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the good practice for returning "large" class private member? [closed]

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?

like image 792
Maksim Avatar asked Dec 26 '22 01:12

Maksim


1 Answers

The difference is in what the users can do with your DataType:

  • with 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.
  • with 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());
like image 156
Sergey Kalinichenko Avatar answered Dec 27 '22 15:12

Sergey Kalinichenko