叼着指针

ckv*_*ckv 5 c++

这段代码是否导致悬空指针.我的猜测是否定的.

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();
}
Run Code Online (Sandbox Code Playgroud)

use*_*715 8

是.将s1传递给SomeFunc时,将调用Sample的复制构造函数.默认的复制构造函数执行浅复制,因此ptr将被删除两次.