-1

can anyone show me more or less how is it implemented because if, for example i have

string str1 = "hello";
string str2 = " world";
string str3 = str1 + str2;

so because the code executes from right to left, this is getting executes, but how? str1 + str2 i mean what the returned value? because it needs to maybe allocate memory for some object and then return it and then how the memory will get free. and also is there a operator+ in the vector class? EDIT thanks to everyone, i was just looking for to understand how the returned object is getting return because 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.

MrDakik
  • 114
  • 6
  • 1
    I think you need to read some documentation to better understand C++.One is about operators: https://en.cppreference.com/w/cpp/language/operators . The other one may be an old answer on stack overflow: https://stackoverflow.com/questions/665781/copy-constructor-in-c-is-called-when-object-is-returned-from-a-function . Hope it helps. – Stefano Buora Nov 10 '20 at 07:13
  • @StefanoBuora ohh, i read and i found out when an object getting created in function, so when the function finished, even if the object get created inside the function, it can still get return and can still be accessible, am i right? – MrDakik Nov 10 '20 at 07:25
  • If you are inside a function and you declare a string (let's call it automatic - not a pointer) it will be undefined behaviour to return that string to the caller). Even though the string itself it's implemented as a pointer to a char array, the class takes care of the object and make sure that the string object will be destroyed at the function exit. If you want to return a string from a function do it by passing a reference to the string, or return a pointer dynamically alocated which _make sure to delete_ when you don't need it anymore in order to avoid _memory leaks_ – Cătălina Sîrbu Nov 10 '20 at 07:29
  • @CătălinaSîrbu exactly!, that what i dont understand, so the function operator+ of the class string, how the function returns an object and then where the memory getting free? – MrDakik Nov 10 '20 at 07:34
  • The compiler introduces the code for creating the temporary for `str1 + str2` and it manages as well its destruction after its limited life-time which may end "after the `;`" of the `str3` initialization. Strictly speaking, I would expect that `str3` is used directly in-place instead of a temporary due to [copy elision](https://en.cppreference.com/w/cpp/language/copy_elision). – Scheff's Cat Nov 10 '20 at 07:37

3 Answers3

5

See this link:

template< class CharT, class Traits, class Alloc >
    std::basic_string<CharT,Traits,Alloc>
        operator+( const std::basic_string<CharT,Traits,Alloc>& lhs,
                   const std::basic_string<CharT,Traits,Alloc>& rhs );

You're basically calling the templated function which boils down to (greatly simplified):

string str3 = operator+(str1, str2);

The operator+ is responsible for constructing a new string out of the two provided and then this gets assigned to str3.


And, based on your comments elsewhere in this question, you seem to be suffering under the misapprehension that things allocated within a function cannot be returned.

That's actually not the case for dynamically allocated things like the content of strings. While it's almost always fatal to return the address of a local object in a function, dynamically allocated memory outlives the function quite nicely.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

A c++ std::string is implemented as a char array. But you will not see this implementation as there is the string class which wraps it for making your life easier. Instead, string class gives you a nice interface to use (as std::string::operator+ for concatenation).

Related to the question, when you add str1 + str2 there is the std::string::operator+ function called and a temporary string will be generated (on the right side of the = operator). The newly created object (let's call it str_temp and consider it looks like this "hello world" ) will be used by str3 to create a new object (of course it will allocate memory dynamically but it will not allocate only 12 elements, but will alocate chunks of bytes). [for example a string with 3 chars can have a length of 3 chars but a size of 15 bytes].

In the example you provided, both str1 and str2 will remain unmodified.

On the following link cppreference std::string::operator+ function signature you can see on what kind of parameters is + going to work when talking about strings. Therefore the next example works as expected, showing three times on the screen the message hello world.

std::string a = "hello ";
std::string b = "world";

std::string result1 = a + "world";
std::string result2 = "hello " + b;
std::string result3 = a + b;

std::cout << result1 << "\n" << result2 << "\n" << result3 << std::endl;
Cătălina Sîrbu
  • 1,253
  • 9
  • 30
3

Operator overloading

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::strings 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

  • Always better to link to cpprefernce.com, e.g. [operator overloading](https://en.cppreference.com/w/cpp/language/operators) it is considered the best secondary reference if not citing the standard. But, a good example explaining the concept. – David C. Rankin Nov 10 '20 at 07:39
  • so is it possible to return this even it is out of the function memory? – MrDakik Nov 10 '20 at 07:39
  • @TiZ_Crocodile I'm not sure what you are asking –  Nov 10 '20 at 07:40
  • Operator overloading is a specific feature of the C++ language, and you can define the overloads needed for your circumstance, for any class. In the case of string concatenation, it is already provided by `std::string`, but this example explains the general way that overloading of operators get defined for any given class. – David C. Rankin Nov 10 '20 at 07:40
  • @DavidC.Rankin My bad, I wrote this answer quickly and didn't realize I cited TutorialsPoint, I fixed the link now –  Nov 10 '20 at 07:42
  • No worries, it was just offered as a helpful tip `:)` – David C. Rankin Nov 10 '20 at 07:42
  • @TiZ_Crocodile I have just given an example of how `+` works between the strings. What's happening behind is a lot of memory management since the whole `std::string` class just works on a `char []` –  Nov 10 '20 at 07:46
  • @TiZ_Crocodile You can read my answer now, I directly answered what you asked after the edit –  Nov 10 '20 at 08:06
  • @AryanParekh do you know maybe if its allowed to return value like that in C? because i learned C and from what i remember its not allowed, this is also the reason i didnt understand – MrDakik Nov 10 '20 at 08:18
  • @TiZ_Crocodile return like what? Do you mean returning by `&` ? –  Nov 10 '20 at 08:23
  • ohhhh sorry now i get it, so the address of the variable is not the same as the address of the variable that is returned because it is just a copy, thank you! – MrDakik Nov 10 '20 at 08:25
  • @TiZ_Crocodile Exactly :) –  Nov 10 '20 at 08:25