ptr
is a pointer to a myClass
, but you don't seem to ever initialize it. In other words, ptr
isn't pointing to anything. It's uninitialized -- pointing in to hyperspace.
When you try to use this uninitialized pointer,
ptr->bubSort(...);
You get Undefined Behavior. You're actually lucky that the application crashed, because anything else could have happened. It could have appeared to work.
To fix this problem directly, you need to initialize ptr
. One way:
class sampleClass
{
public:
sampleClass()
:
ptr (new myClass)
{
}
};
(For an explanation about the funky :
syntax, look up "initialization list")
But this uses dynamic allocation, which is best avoided. One of the main reasons why dynamic allocation is best avoided is because you have to remember to delete
anything you new
, or you will leak memory:
class sampleClass
{
public:
~sampleClass()
{
delete ptr;
}
};
Ask yourself if you really need a pointer here, or would doing without be ok?
class sampleClass
{
public:
myClass mMyClass;
};
sampleClass::func(...)
{
mMyClass.func();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…