Passing a class which holds Dynamic Memory : Methods and their Efficiencies

68 views Asked by At

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:

  1. DataManager(HeavyData one, HeavyData two); //method 1

  2. DataManager(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.

2

There are 2 answers

0
jd. On

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!

0
Ravindra Gupta On

Using pointer and passing the argument by reference is always better then the passing the value. This way you will able to use the many feature of run time polymorphism and it also avoiding the creating the extra HeavyData variable.