Reputation: 717
I have a vector of pointers to objects defined as:
std::vector<queuedImage*> imgBuffer;
I pass it to the constructor of a class by reference:
processThread::processThread(std::vector<queuedImage*> &queueRef);
Within the class processThread I define:
std::vector<queuedImage*> *q;
And within the constructor I make the assignment:
q = &queueRef;
When I come to access elements of the vector which is already populated with objects, the size of the vector is as expected when accessed as:
int qSize = q->size();
Which makes me assume that this should be valid:
q[0]->getData()
Where getData is a member of queuedImage.
However, when I compile this, it is apparently not valid as:
error: base operand of ‘->’ has non-pointer type ‘std::vector<queuedImage*>’
But when I use the . operator instead:
q[0].getData()
I get the compilation error:
error: ‘class std::vector<queuedImage*>’ has no member named ‘getData’
I think that I must be accessing the method incorrectly, but I'm not sure how to do it. Does anyone have any ideas?
Thanks!
Upvotes: 0
Views: 101
Reputation: 1
Besides fixing the syntactical errors to dereference that unnecessary pointer to the vector
(*q)[0]->getData()
you seriously should consider using smart pointers e.g.
std::vector<std::unique_ptr<queuedImage>>
or
std::vector<std::unique_ptr<queuedImage>>
to hold references in vectors, rather than raw pointers.
Which smart pointer type actually to use depends on your use case.
Upvotes: 0
Reputation: 10733
This should be
(*q)[0]->getData();
But why you are unnecessarily creating pointer to vector when you already accepted vector by reference.
Upvotes: 0
Reputation: 302807
When you're doing q[0]
, you're not accessing the first element of the vector, you're actually dereferencing the pointer. q[0]
== *q
== a vector.
What you want to do is call [0]
on the vector that q
is pointing to. To do that, you have to dereference q
first:
(*q)[0]->getData()
Upvotes: 2