Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangling pointer

Tags:

c++

Does this piece of code lead to dangling pointer. My guess is no.

class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}

~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
}
};

void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}

int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal();
}
like image 236
ckv Avatar asked Jun 06 '10 05:06

ckv


1 Answers

Yes. Sample's copy constructor gets called when you pass s1 to SomeFunc. The default copy constructor does a shallow copy, so ptr will get deleted twice.

like image 192
user168715 Avatar answered Sep 21 '22 17:09

user168715