I've been wrestling with this problem, and it really gets under my skin.
I am trying to figure out a way to share data between different classes, using some kind of smart-pointer
in the process, to avoid memory-leaks and dangling pointers.
I've been trying something like this:
This is the "Property-class", the class used to represent data.
The idea is that one class can have different data-members, while avoiding long inheritance-chains.
class IProperty
{
virtual ~IProperty( );
virtual void* data( );
};
template <class T>
class Property
{
T* mData;
void* data( ) { return mData; };
};
Now for the example:
class Foo
{
public:
template< class T >
shared_ptr< IProperty > getProperty( string p_name )
{
propertyMap::iterator it = mProperties.find( p_name );
if( it == mProperties.end( ) ){
shared_ptr< IProperty > xProp = new Property<T>;
mProperties[p_name] = xProp;
return xProp;
};
return it->second;
};
private:
typedef std::map< string, shared_ptr< IProperty > > propertyMap;
propertyMap mProperties;
};
So far, so good, right? Well. The problem arises when I use it.
Foo* pFoo = new Foo( ); shared_ptr< IProperty > pInt = pFoo->getProperty<int>( "Crazy" ); // This works, and I now have one undefined int as a property. int* pIntData = pInt->data( ); // This returns the data *pIntData = 11; // and this sets the property "Crazy" to 11. shared_ptr< IProperty > pString = pFoo->gerProperty<string>( "Crazy" ); // Since the getProperty-method will find a property with the name "Crazy", it will return it. string* pStringData = pString->data( ); // This will try to fetch the data, in my test, the string returned was empty (but then the property was of a different class) *pStringData = "HowCrazyIsThis?"; // This will try to set the property to "HowCrazyIsThis?", and it actually does, except the data is in fact an int, and I wind up with some bogus-value
This is clearly unacceptable. In a multi-user project it creates an almost multithreaded-like dilemma, in which you can never be sure that the data is still valid.
I could maybe try a dynamic_cast, and only change the data if the return-value is not NULL, but I don't really like that solution. Partly because I think it is bad code-standard, and partly because it is slow, and speed is a factor.
Have someone run into this dilemma before?
Regards.

New Topic/Question
Reply



MultiQuote




|