#include <iostream>
struct person_t{
int age;
};
person_t get_person1(){
person_t person;
person.age = 10;
return person;
}
person_t * get_person2(){
person_t *person = new person_t;
person->age = 20;
return person;
}
int main(){
person_t person1 = get_person1();
person_t *person2 = get_person2();
std::cout << person1.age << std::endl;
std::cout << person2->age << std::endl;
delete person2;
return 0;
}
I want to know what is the safest way to return a structure from a function.
As in the answers to the questions in here and here, it is said that when you create a object as in get_person1()
, that object will be destroyed after when it goes out of scope.
But when I search for "How to return a struct from function c++", it suggest me method one (with get_person1()
) (Example here). But I think that method will destroy the object after the function was called and I think method 2 is the safest.
Am I wrong here..? Or any opinion regarding this topic..?
Thank you!!