Domanda

I have an object A with copy constructor and assignment operator which has a member QVector. I use it that way:

QVector<B*> x = GetA().GetVector();
x.at(0)->doSomething();

Now I want to do something with all the B's in the vector but because from GetA() I only got a temporary copy, the pointers got deleted already. Is there a different way then doing something like

A a = GetA();
QVector<B*> x = a.GetVector();
x.at(0)->doSomething();

Is this a problem of my copy constructor or anything else I can fix in the implementation of the copy constructor or the assignment operator?

Thanks

È stato utile?

Soluzione

No, it is not a problem of your copy constructor, but of course this is "something else".

You should return a vector of shared pointers from GetVector() function, because what you really want is to shared ownership on B* objects which are in this vector between some object A and your code presented in this question.

[UPDATE]

That method chaining: GetA().GetVector().at(0)->doSomething(); will work, because it is guaranteed by C++ std that until sequential point (; in this case) all temporaries exist.

If you split this into many lines, as in your example then you should keep the result of GetA() in some named variable.

Some other way is to use extra function, using GetA() as argument (very similar to your own solution):

void foo(const A& a)
{
   QVector<B*> x = a.GetVector();
   x.at(0)->doSomething();
}

foo(GetA());

Or even:

void foo(const QVector<B*>& x)
{
   x.at(0)->doSomething();
}

foo(GetA().GetVector());

Or even in C++11, use lambda expression:

int main() {
  auto foo = [](const QVector<B*>& x)
    {
       x.at(0)->doSomething();
    };
    foo(GetA().GetVector());
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top