Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters/Setters with std::vector<>.push_back(...)

Tags:

c++

std

vector

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.

like image 940
user1043761 Avatar asked Dec 18 '25 00:12

user1043761


1 Answers

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.

like image 125
John Kugelman Avatar answered Dec 20 '25 13:12

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!