tags:

views:

95

answers:

2

I have the following code snippet:

vector<DEMData>* dems = new vector<DEMData>();
ConsumeXMLFile(dems);

if(!udp_open(2500))
{

}        

I want the ConsumeXMLFile method to populate the vector with DEMData objects built from reading an XML file. When ConsumeXMLFile returns, the dems vector is empty. I think I'm running into a pass by value problem.

+3  A: 

By the looks of this the ConsumeXMLFile takes a pointer to a vector so I doubt this is a pass by value problem.

Rob
+2  A: 

Are you at any point reassigning the pointer that is passed into the function? In other words, does your function look anything like this:

void ConsumeXMLFile(vector<DEMData>* dems) 
{
   // ... some code ...

   dems = new vector<DEMData>();

   // ...more code...
}

This is a common mistake that I see beginning C++ programmers (and C programmers) make. What is going on here is that a pointer to the dems vector is being passed by value, which means that if you modify the pointed-to vector, that will affect the the vector possessed by the caller. However if you modify the pointer (which is passed by value) this will not affect the pointer possessed by the caller. After the re-assignment, the dems pointer in ConsumeXMLFile will point to a totally different vector than the dems pointer that the caller holds.

One of the things that makes me suspect that you might be doing this is that this is C++ and there's no clear reason why you would want to pass a pointer to the vector instead of a reference to the vector otherwise.

Tyler McHenry
As Tyler says, passing by reference is a much safer way to pass objects. But if you really must use pointers you can make the param a const pointer to the vector: void ConsumeXMLFile(vector<DEMData>* const dems)
Tony