Reputation: 1
I'm given a simple CTab class which contains such fields as 1 dimensional array's pointer, array's size and following copy constructor:
CTab::CTab(const CTab &cOther)
{
pi_tab = new int[cOther.i_size];
i_size = cOther.i_size;
for (int ii = 0; ii < cOther.i_size; ii++)
pi_tab[ii] = cOther.pi_tab[ii];
std::cout << "Copy ";
}
On the move semantics needs, I also wrote move construcor:
CTab::CTab(CTab && cOther)
{
pi_tab = cOther.pi_tab;
i_size = cOther.i_size;
cOther.pi_tab = NULL;
cOther.i_size = 0;
std::cout << "MOVE ";
}
Previously, I was asked to overload '+' operator so it returns concatenation of 2 arrays. Now, I'm struggling with modification that uses move semantics in order to decrease number of made copies. I have no idea which part of previous code would produce unnecessary copies and if so, how to change the code so it meets the condition of the given task. Any ideas?
Overloaded operator without usage of move semantics:
CTab CTab::operator+(const CTab cOther)
{
CTab newTab;
newTab.bSetSize(i_size + cOther.i_size);
for (int i = 0; i < i_size; i++)
newTab.pi_tab[i] = pi_tab[i];
for (int i = i_size; i < i_size+cOther.i_size; i++)
newTab.pi_tab[i] = cOther.pi_tab[i - i_size];
return newTab;
}
Upvotes: 0
Views: 145
Reputation: 473252
Your CTab
type can gain nothing from being able to move from its arguments to operator+
. The output of any +
operation will have to create a new CTab
that is the sum of the sizes of its arguments. That means allocating new memory for this new object rather than being able to borrow the storage from one of the arguments.
So you should just take a const &
to the parameter and move on.
Upvotes: 5