I was developing some class and came across this question. I have the following class:
struct A { int *p; A() { p = new int(1); cout << "ctor A" << endl; } A(const A& o) { cout << "copy A" << endl; p = new int(*(op)); } A(A&& o) { cout << "move A" << endl; p = std::move(op); op = NULL; } A& operator=(const A& other) { if (p != NULL) { delete p; } p = new int(*other.p); cout << "copy= A" << endl; return *this; } A& operator=(A&& other) { p = std::move(other.p); other.p = NULL; cout << "move= A" << endl; return *this; } ~A() { if(p!=NULL) delete p; p = NULL; cout << "dtor A" << endl; } };
And the following class that has A as a property:
class B { public: B(){} A myList; const A& getList() { return myList; }; };
And this function, which checks a certain value of a variable and returns different objects in different cases:
B temp; A foo(bool f) { A a; *ap = 125; if (f) return a; else { return temp.getList(); } }
Now I want to use this function as follows:
A list1 = foo(true); if(list1.p != NULL) cout << (*list1.p) << endl; cout << "------"<<endl; A list2 = foo(false); if (list2.p != NULL) cout << (*list2.p) << endl;
The purpose of this situation:
The foo function should return (or move) without copying any local object with changes in p if the argument is true , or should return the property of the global variable temp without calling copy constructors A (i.e. return the link myList ), and also should not grab myList from B (it should not destroy myList from B , so std::move cannot be used) if the argument is false .
My question is:
How do I change the function foo to follow the upper conditions? The current implementation of foo works correctly if true and moves this local variable, but if false it calls the copy constructor for list2 . Another idea was to somehow extend the lifetime of the local variable, but adding a const link didn't work for me. Current Output:
ctor A ctor A move A dtor A 125
c ++ reference c ++ 11 move object-lifetime
Egor schavelev
source share