Re: About C++ memory management

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



If you want to properly maintain pointer aliasing, use smart
pointers like boost::shared_ptr<>.

--
=====================================
Alexander Nickolov
Microsoft MVP [VC], MCSD
email: agnickolov@xxxxxxxx
MVP VC FAQ: http://vcfaq.mvps.org
=====================================

"Kürþat" <xx@xxxxxx> wrote in message
news:OwdaQ0zGIHA.3600@xxxxxxxxxxxxxxxxxxxxxxx
Hi,

I have some questions about C++ memory management:

- 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;????

---------------------------------------------------
- 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;
}
}

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? If yes,how
can I know what type of allocation is made by the caller when I design
that class?

Thanks in advance.








.



Relevant Pages

  • Re: About C++ memory management
    ... int * ptr = new int; ... delete ptr; ... But if I copy this pointer like below should I also delete copied ... Foo ...
    (microsoft.public.vc.language)
  • Re: Virtual function and multiple inheritance
    ... virtual int func(); ... class Derived: Foo, Goo { ... Here pF is a pointer to an object with the same memory layout as a Foo and pG is a pointer to an object with the same memory layout as a Goo. ...
    (microsoft.public.vc.language)
  • Re: How to know the memory pointed by a ptr is freed?
    ... > perfectly valid). ... And you're probably assuming that an int* will fit ... > After the call to free, the value if ptr is indeterminate. ... > just copies the bits, but it could, for example, load the pointer ...
    (comp.lang.c)
  • Re: About C++ memory management
    ... int * ptr = new int; ... delete ptr; ... But if I copy this pointer like below should I also delete copied pointer? ... Foo ...
    (microsoft.public.vc.language)
  • Re: How to know the memory pointed by a ptr is freed?
    ... And you're probably assuming that an int* will fit ... the value if ptr is indeterminate. ... just copies the bits, but it could, for example, load the pointer ... knowledge of the implementation (which could easily change with the ...
    (comp.lang.c)