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?
Personally I think a raw pointer (or reference) is okay here. Smart pointers are concerned with managing the lifetime of the object pointed to, and in this case
MyMapperisn’t managing the lifetime of that object,MyClassis. You also shouldn’t have a smart pointer pointing to an object that was not dynamically allocated (which the hash map isn’t in this case).Personally, I’d use something like the following:
Note that this will prevent
MyMapperfrom having an assignment operator, and it can only work if it’s acceptable to pass the HashMap in the constructor; if that is a problem, I’d make the member a pointer (though I’d still pass the argument as a reference, and do_map(&map)in the initializer list).If it’s possible for
MyMapperor any other class using the hash map to outliveMyClass, then you’d have to start thinking about smart pointers. In that case, I would probably recommendstd::shared_ptr, but you’d have to use it everywhere:_hugeIdMapwould have to be ashared_ptrto a dynamically allocated value, not a regular non-pointer field.Update:
Since you said that using a reference is not acceptable due to the project’s coding standards, I would suggest just sticking with a raw pointer for the reasons mentioned above.