Class Instantiation Inside Member Function
Is is safe to instantiate a class inside a memb开发者_Go百科er function of that class? For example, let's say I have class CMyClass
with member function CMyClass::MemberFunc
, and I want to create another instance of CMyClass
inside of CMyClass::MemberFunc
.
void CMyClass::MemberFunc( void )
{
CMyClass * pMyClass = new CMyClass();
}
Is this legal/safe? I know it compiles. What I am concerned about is recursion. Will I run into a recursion error when I instantiate CMyClass
the first time from the main application?
void main( void )
{
static CMyClass * s_pMyClass = new CMyClass(); // Will this cause recursion?
}
Or, will recursion only occur only if the specific member function with the additional class instance is called?
void CMyClass::MemberFunc( void )
{
CMyClass * pMyClass = new CMyClass();
pMyClass->MemberFunc(); // Pretty sure this will cause a recursive loop.
}
In other words, can I safely instantiate a given class within a member function of that class, so long as I do not call that member function of the second instance of that class? Thanks.
This isn't more or less safe than instantiating any other object. Note that in your example at the bottom, the recursion is strictly based on the fact that the method calls itself; it would recurse indefinitely regardless.
In sum: you should be fine.
A (member)function calling itself is known as recursion.
Is this legal/safe?
void CMyClass::MemberFunc( void )
{
CMyClass * pMyClass = new CMyClass();
delete pMyClass ; // newly added.
}
Partially correct. Because every new
operation should have a delete
operation accompanied on the specific instance to return the resources back to free store. Other than memory-leak the above snippet is fine.
Or, will recursion only occur only if the specific member function with the additional class instance is called?
void CMyClass::MemberFunc( void )
{
CMyClass * pMyClass = new CMyClass();
pMyClass->MemberFunc(); // Pretty sure this will cause a recursive loop.
}
Yes, and after some time you should run out of memory as there is no way of destructor being called for the specific instance as CMyClass::MemberFunc
is being called recursively.( assuming delete pMyClass;
as the end statement in the member function )
Also, there is no need to place void
in the argument list when the method don't receive any parameters. I think, it is C
style.
Correct, unless you explicitly call that member function from the second instance created, you will not cause recursion. Of course, recursion isnt always a bad thing, so long as you have some kind of base-case condition to break out.
No, it won't cause recursion - your compiler would flag it as an error if it did. I suspect you really want to create a static instance of your class (e.g. a singleton). Can you post a real-world use-case illustrating what you want to do?
精彩评论