I came accross several questions where answers state that using T* is never the best idea.
While I already make much use of RIIC, there is one particular point in my code, where I use T*. Reading about several auto-pointers, I couldn't find one where I'd say that I have a clear advantage from using it.
My scenario:
class MyClass
{
...
// This map is huge and only used by MyClass and
// and several objects that are only used by MyClass as well.
HashMap<string, Id> _hugeIdMap;
...
void doSomething()
{
MyMapper mapper;
// Here is what I pass. The reason I can't pass a const-ref is
// that the mapper may possibly assign new IDs for keys not yet in the map.
mapper.setIdMap(&_hugeIdMap);
mapper.map(...);
}
}
MyMapper
now has a HashMap<...>*
member, which - according to highly voted answers in questions on unrelated problems - never is a good idea (Altough the mapper will go out of scope before the instance of MyClass
does and hence I do not consider it too much of a problem. There's no new
in the mapper and no delete
will be needed).
So what is the best alternative in this particular use-case?
std::shared_ptr
orstd::tr1::shared_ptr
. In C++0x you could probably usestd::unique_ptr
if you only have one responsible container and don't need to pass the pointer around. – AngelangelasetIdMap
suggests. You'd have to rewrite theMyMapper
class to take a reference in the constructor. But of course that would be a far nicer solution if it worked. – AngelangelaMyMapper
is not managing the lifetime of the object. – Dou