return empty vector by reference

Viewed 2663

I'm returning a vector by reference as shown below and it is getting bit ugly when I want to return an empty vector when there is no item in the map. The following gives warning (returning address of local variable) and to fix it, I have another private member variable vector<ClassA> empty_ and I could return it to avoid this.

I am wondering if there is elegant way to implement this.

const std::vector<ClassA>& GeVector(const std::string& class_id) {
auto iter = class_map_.find(class_id);
if (iter != class_map_.end())
    return iter->second;
return {}; // return empty_;
}

private:
std::unordered_map<std::string, std::vector<ClassA>> class_map_;
vector<ClassA> empty_;
2 Answers

You could use a static variable:

static const std::vector<ClassA> empty;
return empty;

If your method support the option of failure you could throw a exception instead of returning an empty vector.

const std::vector<ClassA>& GeVector(const std::string& class_id) {
    auto iter = class_map_.find(class_id);
    if (iter != class_map_.end())
       return iter->second;

    throw std::exception("Element not found"); // or similar
}
Related