Hey, just wanted to know which one of the following codes will be more optimized for return values. I'm just playing around with writing my own String class and experimenting for optimisation.
Code:
String func (void)
{
return "A String";
}
/* Constructor to initialise a const char* called for typecasting "A String" to my String data type and then
Copy Constructor invoked for returning "A String" */
or
Code:
String& func (void)
{
String* string = new String("Another String");
return string;
}
/* If I do it this way, only the Constructor to initialise const char* is called and the function returns a
reference to that block of memory on the heap but then I run into the problem of de-allocating the
memory. However, for the sake of argument let's say that the memory does get de-allocated at the end of
the program. Then, which of the two functions will be a more optimised way of returning the string? */
Also, I just want to share a mistake I learnt from while playing with my String class.
Code:
String& func (void)
{
String s = "Don't do this";
return s;
// RIP
}
Thanks, any help will be appreciated