I have class A with a public std::list<int> object list_.
Class B, with a pointer to class A a.
In a method in class B...
std::list my_list = a->list_;
my_list.push_back(1);
my_list.push_back(2);
my_list.push_back(3);
I understand that my_list is in fact a copy of list_, which is why the changes are not reflected onto the original list. And for this particular area, I am trying to avoid passing by reference. Without having to do the following...
a->list_.push_back(1);
a->list_.push_back(2);
a->list_.push_back(3);
Would it be possible for me to directly reference the list_ object in A, without having to go through object a every single time?
Thanks
This should work:
std::list<int>& list = a->list_;
list.push_back(1);
list.push_back(2);
list.push_back(3);
Basically I created a local reference variable referencing the list_ member of the A instance.
You can use reference as explained by other answers.
In C++11, you can do even this:
auto add = [&](int n) { a->list_.push_back(n); };
add(1);
add(2);
add(3);
No a->, not even list_, not even push_back(). Just three keystrokes : add.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With