Mixing C and C++, raw pointers and (boost) shared pointers

Posted by oompahloompah on Stack Overflow See other posts from Stack Overflow or by oompahloompah
Published on 2011-03-07T15:33:53Z Indexed on 2011/03/07 16:10 UTC
Read the original article Hit count: 165

Filed under:
|
|
|
|

I am working in C++ with some legacy C code.

I have a data structure that (during initialisation), makes a copy of the structure pointed to a ptr passed to its initialisation pointer.

Here is a simplification of what I am trying to do - hopefully, no important detail has been lost in the "simplification":

/* C code */

typedef struct MyData
{
   double * elems;
   unsigned int len;   
};

int NEW_mydata(MyData* data, unsigned int len)
{
    // no error checking
    data->elems = (double *)calloc(len, sizeof(double)); 
    return 0;
}

typedef struct Foo
{
   MyData data data_;
};


void InitFoo(Foo * foo, const MyData * the_data)
{
   //alloc mem etc ... then assign the STRUCTURE
   foo.data_ = *thedata ;
}


C++ code
-------------
typedef boost::shared_ptr<MyData> MyDataPtr;
typedef std::map<std::string, MyDataPtr> Datamap;

class FooWrapper
{
public:
   FooWrapper(const std::string& key) {
       MyDataPtr mdp = dmap[key];
       InitFoo(&m_foo, const_cast<MyData*>((*mdp.get())));
   }

   ~FooWrapper();

   double get_element(unsigned int index ) const {
      return m_foo.elems[index];
   }

private:
   // non copyable, non-assignable
   FooWrapper(const FooWrapper&);
   FooWrapper& operator= (const FooWrapper&);

   Foo m_foo;
};



int main(int argc, char *argv[])
{ 

   MyData data1, data2;
   Datamap dmap;

   NEW_mydata(&data1, 10);
   data1->elems[0] = static_cast<double>(22/7);

   NEW_mydata(&data2, 42);
   data2->elems[0] = static_cast<double>(13/21);

   boost::shared_ptr d1(&data1), d2(&data2);

   dmap["data1"] = d1;
   dmap["data2"] = d2;

   FooWrapper fw("data1");


   //expect 22/7, get something else (random number?)
   double ret fw.get_element(0);    
}

Essentially, what I want to know is this:

Is there any reason why the data retrieved from the map is different from the one stored in the map?

© Stack Overflow or respective owner

Related posts about c++

Related posts about c