Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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);
}
const Foo &get_foo(const char *msg)
{
static Foo_2 foo2(msg);
return foo2;
}
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 formFoo& get_foo(const char *msg)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question