user3713179
user3713179

Reputation: 361

Pointer of QVector pointer

This is my class constructor:

UndoRedo::UndoRedo(QList<vector_t*> v,
                   QUndoCommand *parent)
    : QUndoCommand(parent)
{  
    ...
    QStringList *sl = &v[0][0];
    ...
}

Where vector_t is

typedef QVector<QStringList> vector_t ;

Whwn I try to set "sl" in this way, the IDE raises this error:

no match for ‘operator*’ (operand type is ‘QList<QVector<QStringList>*>’)

Where I’m doing wrong? Can you help me?

Upvotes: 1

Views: 416

Answers (1)

The biggest problem I see in your questions is that you seem to be severly overcomplicating simple things. First and foremost, Qt's containers are implicitly shared. Thus taking their copies is cheap if said copies are not modified. Thus you can freely pass the outermost container by reference, and have it take the innards by value.

It'd be reasonably cheap, for example, to simply pass QList<vector_t> to your method. It would involve no copying of any kind. Even then, it costs a tiny bit less to pass a const reference instead of a value, namely const QList<vector_t> &.

Why are you taking the address of v? Let's dissect the type of v:

QList<vector_t*> = QList<QVector<QStringList>>*>

To access the innermost element you need to:

  1. Access a list element: v[0]
  2. Dereference the pointer: *exp
  3. Access the vector element: exp[0]

By exp I mean the preceding expression, taken as a unit.

Thus:

QStringList & sl = (*(v[0]))[0];

This is C++, not C, you should use a reference instead of a pointer.

If you insist on a pointer:

QStringList * sl = *((*(v[0]))[0]);

But then you can do silly things like delete sl or free(sl) and it will compile but will result in, maybe, your hard drive getting formatted.

Upvotes: 4

Related Questions