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 (rand开发者_JAVA百科om 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?
Using operator[] of map to insert element will erase the previous data stored at the same key, try using insert instead. Same deal with getting data from map, operator[] will create an element if your Key is not stored, try using find instead.
Also const_cast<MyData*>((*mdp.get()))
will cast a MyData in Mydata*, const_cast<MyData*>(mdp.get())
will be good ...
精彩评论