C++/Pointers

Advertisement


Question
Hi Vijayan,

How are you.I have some doubts in useing pointers.

1.For every pointer i have to deallocate the memory or is it for only  the pointers who are created with using  "new"?
2.Useing references we can't allocate memory dynamically ? and we can't create objects useing references? is it only for referring objects?.

I have asked most of  my friends on pointers and references , They are suggesting me use references only. use pointers when your creating the objects . Let  clarify me on this scenarion. i have a  funtion

void strToUpper( string *str){  
   string *sv=0;
   sv=str;
   sv->append("hi");
   cout << *sv << endl;
}

In this funtion parameter "str" will be never null, eventhough im useing pointer only instead of references.

In this funcion any memory leak will happen ? what are the possibilitys for happening memory leak in this function becoz of iam useing pointer instead of references.

Many thanks in Advance
 Sireesh.  

Answer
1.For every pointer i have to deallocate the memory or is it for only  the pointers who are created with using  "new"?

Objects need to be destroyed and memory needs to be deallocated for every OBJECT allocated using new. Many pointers may be pointing to the same object (this is called "aliasing"); you invoke delete on a pointer, what is destroyed is the object pointed to. Assuming that A is a class,

void foobar()
{
  static A object1 ;
  A object2 ;
  A* p1 = new A() ;
  A* p2 = &object1 ;
  A* p3 = &object2 ;
  A* p4 = p1 ; // p4 and p1 are aliased

  delete p1 ; // object allocated using new, call delete on the pointer
}

simple rule: invoke delete on the pointer returned by new (or a copy of it) once and only once. Do not invoke delete on any other pointer.
  

2.Useing references we can't allocate memory dynamically? and we can't create objects useing references? is it only for referring objects?.

Yes. References are used only to refer to existing objects.


> In this funcion any memory leak will happen ?
no. a memory leak will never happen in this function, it has not created any object using new.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.