I read the following code
student* input(string name, int age)
{
student *st = new student(name,age);
return st;
}
where student
is just a simple class with following function and member
class student{
public:
student(string na, int ag);
void show();
private:
string name;
int age;
};
show
is just a function to print a sentence. Main function is the following
int main(){
student *st = input("guagua",25);
if(!st){ cout<<"no pointer"<<endl;}
st->show();
delete st;
return 0;
}
My understanding is that because I use new
so in the main function I need delete st
. If I use the following code the take the place of student *st = new student(name,age);
, do I still need to delete st
?
student te(name,age);
student *st;
st = &te;
If not because now st is a raw pointer, why people need new
? We can all use the similar way to take the place of new
.
Another problem is that some people suggest to use smart pointer to avoid we forget delete a pointer. Then I just use raw pointer in every place like above, it seems we do not need delete
at all? I know there must some place I didn't understand, hope you can help me. Thanks