3

For some reason this doesn't work. It compiles file, but no items are added to this vector when using a getter.

E.G.

class class_name {

    public:
        inline std::vector<int> get_numbers() { return m_numbers; }    

    private:
        std::vector<int> m_numbers;
}

....

{
    class_name number_list;
    number_list.get_numbers().push_back(1);
}

If I do it directly (m_numbers.push_back(1)) it works, but if I pull it out with a getter it won't add anything.

user1043761
  • 696
  • 6
  • 22
  • Member functions defined inside the class are already implicitly inlined, so the `inline` keyword is not needed (although some people may have other reasons for putting it there). – Jesse Good Oct 12 '12 at 03:07

1 Answers1

9

Return the vector by reference if you plan to modify it:

inline std::vector<int> &get_numbers() { return m_numbers; }  
                        ^

Without the ampersand a copy is returned.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578