Question

I´m trying for several hours now to get this right. What i want to do is have a map of vectors (the vectors contain pointers to objects) stored in an unnamed namespace. Classes are then allowed to access the data in the vector via a function call.

//DataHandler.cpp

#include "DataHandler.h"

using std::vector;
using std::unordered_map;

namespace DataHandler
{
  namespace
  {
    unordered_map< unsigned int, vector<MyClass*> > data_map_;
  }

  void receiveData(unsigned int key, vector< MyClass*>& data_vec)
  {
    //check if key already exists:
    unordered_map<unsigned int, vector<MyClass*> >::iterator it;

    it = data_map_.find(key);
    if (it != data_map_.end())
    {
      data_vec = it->second;
      return;
    }

    //generate new key with new data
    data_map_.insert(make_pair(key, vector< MyClass*>()));

    data_map_[key].push_back(new MyClass(/*some constructor arguments*/));
    // ... push back some more instances of MyClass ...

    //finally:
    data_vec = data_map_[key];
    return;
  }
}

In some other class I do this for getting the vector:

//SomeOtherClass.cpp

#include "SomeOtherClass.h"
#include "DataHandler.h"

using std::vector;

void SomeOtherClass::aMethod()
{
  vector<MyClass*> first;
  vector<MyClass*> second;
  vector<MyClass*> first_again;

  DataHandler::receiveData(1, first); //works fine
  DataHandler::receiveData(2, second); //works fine
  DataHandler::receiveData(1, first_again); // <- strange behavior or segfault here
}

So everything works as expected, besides if I want to access a vector which had previously been filled with MyClass instances - then I get strange behavior or a segmentation fault. Can someone explain to me why this is so and how this is done right?

Thanks!!

Was it helpful?

Solution

I can't see any specific problem, so this isn't an answer but is too long for a comment. I'll mark it community wiki. Anyway, why not have a std::unordered_map<unsigned, std::vector<MyClass>> and get rid of all the pointers and lifetime issues? SomeOtherClass::aMethod() can do an insert, which returns an std::pair<iterator,bool> - just save that iterator if you want access to the MyClass elements later in aMethod. As is, if you have some pointers in first_again, they're clobbered inside receiveData() with whatever pointers are in first: there are lots of ways that could be a memory leak, but I can't say for sure without seeing more of your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top