-
October 20th, 2015, 06:08 AM
#1
Destructor for a pointer in class
Hi,
Sorry I have not been here for long .. In my last visit got some really good tips to improve my c++
I have a legacy class something like this and i added the following structs inside.
class CClass : public CBaseClass, public ClassC
{
public:
virtual ~CClass();
struct CreateSessInfo
{
// Following fields are valid when the CCR num is 0
CreateSessionReq stCrSessReq;
CClass * pClassInstance1;
};
struct DedBearerInfo
{
CClass * pClassInstance2;
u8 nProcId;
};
};
Now my query is that , in the existing destructor for this class, I need to delete these pClassInstance1, and pClassInstance2
thanks,
~p
-
October 20th, 2015, 07:16 AM
#2
Re: Destructor for a pointer in class
You don't show where pClassInstance1 and pClassInstance2 are created (using new).
If they are created inside CClass/DedBearerInfo, then you have to delete them in the destructor. You might be better off using a smart pointer like std::unique_ptr/std::shared_ptr (C++11).
HTH,
Richard
And next time, please use code tags to properly format your code.
Last edited by Richard.J; October 20th, 2015 at 07:23 AM.
Reason: fixed typo
-
October 20th, 2015, 07:31 AM
#3
Re: Destructor for a pointer in class
Thanks a lot Richard,
I have tried to use the same format as the existing code.
These pointers are assigned as follows: In the class member function:
CClass::memberfunction()
{
:
stCrSessInfo.pCpgwInstance = this;
:
}
-
October 20th, 2015, 07:41 AM
#4
Re: Destructor for a pointer in class
Well, if you just use the pointer to store a reference to the 'parent' class, you must not delete it. Otherwise, in the CreateSessInfo destructor you would delete your object containing the CreateSessInfo instance.
Basic rule: if you create an object using 'new', you have to 'delete' it.
If you just store the address of something you did not create, don't delete it.
-
October 20th, 2015, 07:46 AM
#5
Re: Destructor for a pointer in class
Thanks a lot Richard, your advice is much appreciated
-
October 20th, 2015, 09:47 AM
#6
Re: Destructor for a pointer in class
Originally Posted by pdk5
Thanks a lot Richard,
I have tried to use the same format as the existing code.
to preserve the "same format as the existing code" you must use CODE tags. See the Announcement: ..., section Before you post....
Victor Nijegorodov
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|