Why so much allocation? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why so much allocation?

Hi I am aware that string concatenation is costly operation. I am just trying to understand what is exactly happening when we perform A = A+B Refer below code: https://code.sololearn.com/cwznVtPL3ARH As soon as we allocated str, it is more than small string optimization and hence it allocates memory on heap. So , First output line is something I got clearly. Then str1 is small enough and no allocation on heap for this. So, no particular line in output due to this code line. Now, when str = str + str1; it is compiler dependent and generally most of the compiler double the allocation. so, I can digest output showing allocation of 39 bytes. But what about additional 20 bytes allocated earlier? I thought that additional 20 is cost of copy constructor. But it is not true I believe. [verify this by just changing initial value of str1 same as str. Now, i was expecting two copy constructor call but there are no two extra allocation before + operation] Any thought on this?

26th Dec 2021, 5:28 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Answer
+ 2
'str + str1' concatenates the two strings to create a new one (operator+): first it copy-contruscts the resulting string with the lhs(str) and then appends (operator+=) the rhs(str1) to it
26th Dec 2021, 7:49 PM
Angelo
Angelo - avatar