简体   繁体   中英

Lifetime and usefulness of an object that is created inside an if statement in a method

This ic the class I want to use to understand destructors.

#include iostream
using namespace std;

class Student{
public:
Student(int num = 0)
{
id = num;
}
}

This is the method

void bar(int a)
{

if( a == 5)
Student S(5);

cout<<"after if"<<endl;

}

The thing is that if a = 5; object S of Student class is created and the object's life time ends with the if loop. The destructor called before the line after if. So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore? Or can they somehow be useful?

I'm not entirely sure what you mean when you ask about usefulness .

If you only need an object to exist for a very short time but you still might want to hold on to that data, you can use std::shared_ptr to use smart pointers to dynamically allocate memory for the objects on the heap. The objects are very quick to access and is an easy way to make trivial use of them. You could do this with raw pointers but smart pointers are just safer, in that you won't ever get memory leaks from forgetting to delete a raw pointer:

std::shared_ptr<Student> stu_ptr;

if (a == 5) 
    stu_ptr = (new (Student(a)));

stu_ptr->someClassFunction();

stu_ptr still exists after the if statement. If you wanted to do multiple checks/conditions you could keep reassigning that stu_ptr or, due to the nature of shared pointers, you could make new shared pointers to the same Student object to fulfill other trivial calculations/functionalities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM