V
V
varnak522019-01-09 18:58:04
C++ / C#
varnak52, 2019-01-09 18:58:04

Why does a function return a temporary object?

Good afternoon!
I'm taking a course in C++ on Stepic
The task is as follows:
You are given a class Foo:
struct Foo {
void say() const { std::cout << "Foo says: " << msg << "\n"; }
protected:
Foo(const char *msg) : msg(msg) { }
private:
const char *msg;
};
As you can see, the creator of the class did not want to be used and "hid" the class constructor. But you really need an object of this class to pass it to the foo_says function:
void foo_says(const Foo& foo) { foo.say(); }
In this challenge, you need to implement the get_foo function (whose signature is intentionally not given in full in the challenge, you need to think about it and derive it yourself) so that the following code compiles and works:
foo_says(get_foo(msg));
Where msg is an arbitrary C-style string.
Implementation Requirements: You are allowed to inject any helper functions and classes while completing the assignment. You may not change the definition of the Foo class or the foo_says function. You don't need to enter or exit anything. It is not necessary to implement the main function

The task was solved by:

struct Foo_2 : Foo
{
    Foo_2(const char *msg) : Foo(msg) {}
};
Foo get_foo(const char *msg)
{
    Foo_2 temp(msg);
    Foo * r = &temp;
    return *r;
}

But I don't understand why this is happening.
Can you please tell me why it is possible to use a temporary value on exit from the function? And is it right to do so, if not, how should it be?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2019-01-09
@varnak52

There will not be a temporary object, but the same object that you created inside the function. It won't even copy. Although, your object can be cut off here, so another question. Read about RVO/NRVO.
I tweaked your solution a bit:

Foo get_foo(const char *msg)
{
    return Foo_2(msg);
}

It will be better this way.
But! It is important to understand here that it is impossible to do this in real code, because an object of class Foo_2 will, under certain conditions, be truncated to an object of class Foo. In your case, this is not a problem. But you can rewrite something like this, for example:
const Foo &get_foo(const char *msg)
{
    static Foo_2 foo2(msg);
    return foo2;
}

This code is also not suitable for all cases, because. get_foo will always return the same object with the same message.

V
Vasily Melnikov, 2019-01-09
@BacCM

At you here not the internal variable is returned, and a copy of object.
*r a new object is created that is initialized by the copy constructor from the local one, the same thing would happen if it returned temp
The error would be with a function of the form
Foo& get_foo(const char *msg)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question