pass by value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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();
}


Here, SomeFunc passes s1 by value.

Will the next line "s1.PrintVal();" work fine?
There is a problem.

The default copy in Sample will copy the value of the pointer. So when Sample is passed by value, both copies have a ptr that have the same value, which means they point to the same thing.

When the temporary copy is destroyed, it deletes the pointer. The original copy is left with ptr pointing to memory that's been freed. This is called a dangling reference, and it's bad.

The function s1.PrintVal() will still "work", in that it will print an integer, but the memory can be resused by something else.

Futher more, when s1 is destroyed, it attempts to delete memory that's already been deleted. This is really bad.
Topic archived. No new replies allowed.