copy constructor - How to use members of temporary instance in C++? -
i have object copy constructor , assignment operator has member qvector. use way:
qvector<b*> x = geta().getvector(); x.at(0)->dosomething(); now want b's in vector because geta() got temporary copy, pointers got deleted already. there different way doing like
a = geta(); qvector<b*> x = a.getvector(); x.at(0)->dosomething(); is problem of copy constructor or else can fix in implementation of copy constructor or assignment operator?
thanks
no, not problem of copy constructor, of course "something else".
you should return vector of shared pointers getvector() function, because want shared ownership on b* objects in vector between object a , code presented in question.
[update]
that method chaining: geta().getvector().at(0)->dosomething(); work, because guaranteed c++ std until sequential point (; in case) temporaries exist.
if split many lines, in example should keep result of geta() in named variable.
some other way use function, using geta() argument (very similar 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 in c++11, use lambda expression:
int main() { auto foo = [](const qvector<b*>& x) { x.at(0)->dosomething(); }; foo(geta().getvector()); }
Comments
Post a Comment