Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

deleting memory

Status
Not open for further replies.

Maurader

Technical User
May 8, 2002
59
CA
If I have a function
struct myStruct{
double myDouble;
}

func(vector <myStruct> &myVector){
myStruct dynamicMyStruct;
dynamicMyStruct = new myStruct;
myVector.push_back(dynamicMyStruct);
}

how do I delete the memory associatted with dynamicMyStruct? I cannot delete it at the end of the function since I still need the contents of the vector after the function returns...

Thanks!
 
you can create a &quot;constructor&quot; and a &quot;destructor&quot; for your structure so then you will allocate memory for &quot;dynamicMyStruct&quot; in your &quot;constructor&quot; and delete back in your &quot;destructor&quot;.

Code:
struct myStruct
{
   myStruct(); //constructor
   ~myStruct(); //destructor
   double myDouble;
};

myStruct *dynamicMyStruct;

myStruct::myStruct()
{
   dynamicMyStruct = new myStruct;
}

myStruct::~myStruct()
{
   delete dynamicMyStruct;
}

 
will the memory be cleared if i said myVector.clear()?
 
what if it's a built-in type like double/int?
 
I think you have a problem in func() :

You cannot push_back() a pointer on a vector<myStruct> (The vector doesn't hold pointers)

Instead you should push_back(a_myStruct_instance)
You don't need to bother with memory allocation : vector will do that.

If you happen to have a pointer to a myStruct object use push_back(*ptr), and delete ptr afterwards if required.


/JOlesen
 
Vector doesn't need to keep objects sorted, so you won't need it here.

This code compiles fine my computer :

#include <vector>
using namespace std;

struct myStruct{
double myDouble;
};

void func(vector <myStruct> &myVector)
{
myStruct s;
myVector.push_back(s);
}


void main(void)
{
vector<myStruct> vec;

func(vec);
}

/JOlesen
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top