Forget std::string
. Imagine you have a simple position class, which holds x
and y
coordinates in a 2 dimensional world
struct Position {
int x;
int y;
Position( const int x, const int y)
: x(x), y(y)
{}
};
int main()
{
Position s( 5, 10 );
Position t( 20, 30);
}
Now let's say the I wanted to add these positions, so that I get a new position where x = 25 , y = 40
. Can I just use +
?
Position sum = s + t; // error
^
No match for operator '+', Operands are `Position`, `Position`
~~~~~~~~~~~~~~~~~~~~~~
How is the compiler supposed to know how to add Position
and Position
? As I said, operator overloading.
For this example it would be
friend Position operator+(const Position& r, const Position& l)
{
return Position(r.x + l.x, r.y + l.y);
}
Now the error disappears, and the new object formed will have the correct values.
The same way, std::string
has overloaded operator+
which takes two other std::string
s objects and concatenates them.
Once it constructs the new string, it copies it into str3
.
I thought that if the object is created inside the function so it'll
get destroy after the function finished, but its not, so i can return
an object that got created inside a function.
Consider this example
int foo()
{
int temp = 10;
return temp;
}
int main()
{
int i = foo();
std::cout << i;
}
10
You're not actually returning temp
from the function. That variable is completely destroyed. What you are doing is returning a copy, which gets assigned to i
.
What will fail is
int& foo()
{
int temp = 10;
return temp;
}
int main()
{
int& i = foo();
std::cout << i;
}
Make sure to disable optimizations when you test this
This fails because now you are returning a reference to an object that is destroyed. Note that it isn't necessary this has to fail. Anything that happens after doing the above is undefined behavior.
The compiler is god so it just might translate your code into
int main()
{
int i = 5;
std::cout << i;
}
Because of all this, the compiler will decide to do something else because copying will be in-efficient if the object is huge, that is return value optimization