Назад к задачамПолучайте помощь с лайвкодингом в реальном времени с Sobes Copilot
Junior — Senior
5
Refactoring methods that return references to temporary objects
Условие задачи
In the class ForInterview the functions get_ref() currently return a reference to a locally created instance, which leads to a dangling reference. Refactor the implementation so that the returned reference remains valid after the function exits.
class ForInterview {
public:
struct S {
int x = 1;
};
const S& get_ref() const {
S s;
return s;
}
S& get_ref() {
S s;
return s;
}
void run() {
const S& cs = get_ref();
S& s = get_ref();
std::cout << cs.x;
std::cout << s.x;
}
};