Reputation: 2129
Giving two classes A and B which B has a uinque_ptr of A!
class B {
unique_ptr<A> a;
B() {
}
~B() {
}
}
and A has a method returning a vector of unique_ptr of itself as below:
vector<unique_ptr<A>> const& A::getObjects() const {
return this->myVector;
}
Now I want to implement a method in B which checks if the unique_ptr to A has been existing return the vector in A otherwise a reference to an empty vector or Null as error:
vector<unique_ptr<A>> const& B::getObjects()const{
if (this->a.get()!=nullptr){
return this->a->getObjects()
}
//ToDo an empty object or null
}
My question is what can I return in function above? returning nullptr is giving an compile error. returning the code below:
vector result; return result;
will cause a warning: reference to local variable result returned [-Wreturn-local-addr]
and returning {} (return {}) give me another warning:
returning reference to temporary [-Wreturn-local-addr]
So my question is what can I return without giving a warning or an error?
Upvotes: 2
Views: 319
Reputation: 1
So my question is what can I return without giving a warning or an error?
You can have a static vector<unique_ptr<A>> nullresult;
in your function, and return that one in case:
vector<unique_ptr<A>> const& B::getObjects()const{
static vector<unique_ptr<A>> nullresult;
if (this->a.get()!=nullptr){
return this->a->getObjects()
}
return nullresult;
}
Upvotes: 3