I have a class that holds some big amount of data, called HeavyData
. This class Follows the rule of three (It has
overridden the copy-constructor, copy-assignment operator and the destructor to be able to copy the member variable someBigAmountOfData
correctly when copying the class and to be able to free the class without causing memory leaks).
The DataManager
class has two member variables of type HeavyData
. (See Below)
class HeavyData
{
public:
HeavyData();
HeavyData(const HeavyData& that);
HeavyData& operator=(const HeavyData& that);
~HeavyData();
private:
void* someBigAmountOfData; //maybe a few hundred bytes (on the heap, of course)
size_t sizeOfData;
};
class DataManager
{
public:
DataManager();
//method 1
DataManager(HeavyData one, HeavyData two):
one(one),
two(two)
{
}
//method 2 (which I think is more effective than method 1)
DataManager(const HeavyData& one, const HeavyData& two):
one(one),
two(two)
{
}
private:
HeavyData one;
HeavyData two;
};
THE PROBLEM :
The DataManager
class has two constructors as follows:
DataManager(HeavyData one, HeavyData two);
//method 1DataManager(const HeavyData& one, const HeavyData& two);
//method 2
The problem is in choosing a constructor from the above two. Which one do you think is more efficient ? And Why ?
In think that the 2nd constructor (method 2) is more efficient.
passing by const reference will avoid an extra copy as stack values. however, assignment of member variable during construction also copies. maybe better: use a shared_ptr to allocate your HeavyData, and pass that around (never copy it to begin with!). of course, it depends on how Heavy we're talking.
standard advice applies, of course: try both, and step through the copying. measure the performance yourself, too!