In C++, is there a way to implement this behavior:
#include <assert.h>
class A
{
/* ... */
}
int main()
{
A a1 (1);
A a2 (2);
A a3 (1);
assert (&a1 == &a3);
assert (&a2 != &a1);
}
Basically, I want to cache the object on its construction. I am not simply passing an int in the real implementation, I'm passing a std::vector <std::string> and if the std::vector <std::string> is the same as a previously constructed object, the object constructed should be identical.
I tried to implement this with a static cache, but this didn't work since the "this" pointer cannot be assigned to when we have identified that this object is to be a duplicate.
I think this is an impossible task because of the semantics of constructing.
Should I just have a purely static class that holds the cache and also constructs an "A" if it is not in the cache, and then returns a pointer to the object. Then this pointer can be used, and all users of A will have to construct their objects through the cache class and work with pointers to A rather than A's.
edit:
class AConstructor
{
static Cache c; // probably a std::map
static A* construct (K key)
{
if (key not in c)
c.add (value_pair (key, new A (key)));
return c[key];
}
};
int main()
{
A* a1 = AConstructor::construct (1);
A* a2 = AConstructor::construct (1);
assert (a1 == a2);
}
The problem with this approach is that it involves changing all my code to include pointers to A, which may make sense or not.
The actual problem I'm abstracting is I have a set of GLSL shaders with a list of #define's that go along with a generic shader to customize it. Caching shaders allows me to change shaders much less often if objects share the same properties (like, "SHADOWS", or "TEXTURED").
[Edited by - solinent on May 31, 2009 5:34:07 PM]