0

I need to use QMap<QTcpSocket*, QString> just to keep a name of every connection.

I was told that using a complex object like QTcpSocket as a key is not ideal since the way map compares key, it could think there is a duplicate while it isn't.

So I would be apparently be better to use QMap<QString, QTcpSocket*> instead.

I was not able to find "good practice" information on it. Is there any ground to this? Are some objects more/less recommended than others to use as keys?

Carol
  • 1,852
  • 26
  • 29
  • 2
    If you use pointers to objects as keys, it is not possible to have duplicates, because it is impossible to have two different objects with the same address. So `QMap` looks good to me. – vahancho Aug 19 '14 at 14:58
  • Would it be different if it was not a pointer? – Carol Aug 19 '14 at 17:18
  • If it is not a pointer, QMap will need to compare two QTcpSockets. You will need to implement your own `operator<` for them. – vahancho Aug 19 '14 at 20:00

1 Answers1

3

As @vahancho mentioned, using a pointer to the object in this case is not a problem.

However, as you're wanting to keep a name of each connection, consider that QTcpSocket is a QObject.

With this in mind, you can call the function setObjectName( const QString & name) to name the object and the function objectName() to retrieve it, as described in the documentation for QObject.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85