Expectedy copy constructor not elided
Feb 18, 2020 at 9:22am UTC
I have the following class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
class IntArray
{
private :
int m_size;
int *m_array;
public :
IntArray(int s)
{
m_array = new int [s];
}
IntArray(const IntArray &arr): m_array(nullptr )
{
std::cout << "Called copy constructor." ;
m_size = arr.m_size;
m_array = new int [arr.m_size];
for (int i { 0 }; i < arr.m_size; ++i)
{
m_array[i] = arr.m_array[i];
}
}
~IntArray()
{
delete [] m_array;
}
int &operator [](int index) const
{
assert(index >= 0 && index < m_size && "Index is out of range." );
return m_array[index];
}
friend std::ostream &operator <<(std::ostream &out, const IntArray &arr);
friend int runEx9_x_3();
};
Operator overloading isn't relevant I think.
This code executes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
int runEx9_x_3()
{
IntArray a{ 5 };
a[0] = 5;
a[1] = 8;
a[2] = 2;
a[3] = 3;
a[4] = 6;
std::cout << a << '\n' ;
IntArray &ref{ a };
IntArray b(1);
b = a;
std::cout << "(&b == &a) = " << (&b == &a) << '\n' ;
std::cout << "(b.m_array == a.m_array) = " << (b.m_array == a.m_array) << '\n' ;
std::cout << "(&(b.m_size) == &(a.m_size)) = " << (&(b.m_size) == &(a.m_size)) << '\n' ;
a.m_array[2] = 111; // last change. Modify b.m_array too. Why?
std::cout << b << '\n' ;
std::cout << a << '\n' ;
return 0;
}
The output is:
[5 8 2 3 6 ]
(&b == &a) = 0
(b.m_array == a.m_array) = 1
(&(b.m_size) == &(a.m_size)) = 0
[5 8 111 3 6 ]
[5 8 111 3 6 ]
I expect that the last change which I did on underlying array of "a" object affect only this. But I see that in fact "b"'s array is the same. So I conclude that my copy constructor is elided. Why? As far as I'm concerned, it shouldn't. Can anybody explain me why this behavior?
Thanks.
Last edited on Feb 18, 2020 at 9:25am UTC
Feb 18, 2020 at 9:36am UTC
Your copy constructor is not elided. It's just not being used, because you're never copy constructing anywhere in your code.
1 2
IntArray b(1); // This is not a call to a copy constructor
b = a; // Neither is this - this is an assignment operator
This is the assignment operator:
1 2 3 4 5 6
IntArray& operator =(IntArray other)
{
std::cout << "Called assignment operator." ;
// Write code here
}
Because you didn't write one yourself, you get a default one. Add that assignment operator to your code and you'll see it get called.
This is a copy constructor use:
IntArray b(a);
Last edited on Feb 18, 2020 at 9:51am UTC
Feb 18, 2020 at 12:49pm UTC
Got it know. And fixed it. Thanks.
Topic archived. No new replies allowed.