Re: About C++ memory management
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Tue, 30 Oct 2007 18:28:41 -0400
Krat <xx@xxxxxx> wrote:
- I know that every pointer allocated by using new operator should be
deleted:
int * ptr = new int;
.
.
delete ptr;
But if I copy this pointer like below should I also delete copied
pointer?
int * ptr = new int;
int * ptr1 = ptr
.
.
delete ptr;
delete ptr1;????
No. You are not allocating a pointer: you are allocating a block of
memory, and making the pointer point to it. Similarly, what you free is
not the pointer, but the block of memory it points to. Now, you can have
two, or three, or ten pointers all pointing to the same block. It
doesn't matter - it's still the same piece of memory and only needs to
be freed once (freeing it more than once is actually a bug in itself).
---------------------------------------------------
- Consider I have a class which have a pointer member which is
supplied by the caller :
class Foo
{
private:
int * m_ptr;
public:
Foo (int * ptr)
{
m_ptr = ptr;
}
}
This is an unfortunate design. Foo instance is now at the mercy of
whoever constructed it to ensure that the pointed-to memory lives longer
than the Foo instance itself.
Now let us see two situations :
A) int n;
Foo foo (&n);
B) int * ptr;
ptr = new int;
Foo foo (ptr)
In A, there is no need to delete passed pointer in the calss but in B
passed pointer should be deleted by the class, shouldn't it?
Well, it should be deleted by _somebody_, not necessarily by Foo. If Foo
does delete the pointer, it should carefully document that the pointer
passed to Foo's constructor must be allocated with new. Then code in A
would be in error, as it would use Foo in violation of its documented
behavior.
If
yes,how can I know what type of allocation is made by the caller when
I design that class?
You can't know that. That's why Foo, as written, demonstates a poor
design.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
.
- References:
- About C++ memory management
- From: Kürşat
- About C++ memory management
- Prev by Date: About C++ memory management
- Next by Date: Re: About C++ memory management
- Previous by thread: About C++ memory management
- Next by thread: Re: About C++ memory management
- Index(es):
Relevant Pages
|