C ++ STL containers with pointers: a few questions

Say you have type T and subtypes TSub1 , TSub2 , etc.

Some of these subtypes are initialized with new TSub(...) . The resulting pointers are then stored as elements in:

 list<T*> tsList; 

The same pointers are also used as keys in:

 map<T*,V> tsMap; 

Now consider iterating over tsList with the tIter tIter variable.

Here are my questions:

  • Will tsMap[*tIter] and tsMap.find(*tIter) successfully find the correct associated value?

  • Will delete *tIter successfully free a full block of memory is allocated for the corresponding TSub , although the STL sees the type as T

  • Suppose that there is a specific method T::foo() and override TSub::foo() .

    Will (*tIter)->foo() call T::foo() or TSub::foo() ?

Context: each TSub must be created in singleton mode, but must be stored in such a way that iterative considerations are considered as supertypes using methods overridden in the subclass called.

I would really appreciate an informed explanation. Thank you for your time!

+4
source share
2 answers

Will tsMap [* tIter] and tsMap.find (* tIter) successfully find the correct associated value?

Yes, but tsMap [* tIter] will create a default value if it does not find the key.

Delete * tIter will successfully free the allocated memory block for the corresponding TSub, although the STL sees the type as T?

If and only if the destructor T is virtual

Assume that there is a specific method T :: foo () and overrides TSub :: foo ().

Will (* tIter) → foo () call T :: foo () or TSub :: foo ()?

It will call T :: foo if T :: foo is not virtual. Otherwise, it will call TSub :: foo ()

+6
source

I suggest looking at the library of pointer containers from boost.

In addition, I would suggest that

Will tsMap [* tIter] and tsMap.find (* tIter) successfully find the correct associated value?

depends on the definition successfully. If the pointer identifier is a key identifier, yes. If you need to compare pointee objects instead, you need to provide an object for the comparison function (the called type in C ++ 0x).

Rather inefficient PoC: (see http://ideone.com/TpgLw )

 #include <map> #include <functional> template <typename T> static bool indirectLess(const T* a, const T* b) { if (a==b) return false; if (!a) return true; if (!b) return false; return std::less<T>()(*a, *b); } typedef int T; typedef int V; int main() { typedef bool (*cmp_t)(const T*, const T*); std::map<T*,V,cmp_t> tsMap(&indirectLess<T>); } 
0
source

All Articles