Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing in c++ without passing by reference

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

like image 300
Joshua Avatar asked Nov 30 '22 02:11

Joshua


2 Answers

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.

like image 190
Constantinius Avatar answered Dec 01 '22 16:12

Constantinius


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.

like image 33
Nawaz Avatar answered Dec 01 '22 17:12

Nawaz