void ref(std::string& str)
{ (void)str; }
void copy(std::string str)
{ (void)str; }
int main()
{
std::string str = "Hello World";
for(size_t i = 0; i < 10000; i++)
ref(str);
}
Why do I get the same amount of allocations when I call 10000 times ref(str)
or copy(str)
.
As far as I understand, making a copy of an object should allocate new space for a new object.
How Does std::string
make to not reallocate this place and still have a copy object in a function call.
The output of valgrind for 10000 calls to copy
==19794== HEAP SUMMARY:
==19794== in use at exit: 0 bytes in 0 blocks
==19794== total heap usage: 1 allocs, 1 frees, 72,704 bytes allocated
Why I don't have 10000 allocation ?
The output of valgrind for 10000 calls to ref
==19794== HEAP SUMMARY:
==19794== in use at exit: 0 bytes in 0 blocks
==19794== total heap usage: 1 allocs, 1 frees, 72,704 bytes allocated
The result you found might vary based on the compiler and its optimization settings.
Most modern compilers apply optimization here.
When you're calling the copy function, the compiler applies copy elision and optimizes the copy of the std::string
object. Instead of allocating new memory for the copied object, the compiler directly reuses the existing std::string
object, eliminating the need for additional allocations.
Learn more about copy elision from here