Joshua
Joshua

Reputation: 1584

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

Upvotes: 4

Views: 194

Answers (6)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

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.

Upvotes: 7

Omaha
Omaha

Reputation: 2292

I'm curious as to why you are averse to passing by reference.

You could add member functions to class A to handle manipulating the member list, instead of requiring callers to invoke the functions on the list itself. I don't know if this fits your usage, though.

Upvotes: 1

Konrad
Konrad

Reputation: 40947

Why don't you want to use a reference? Either this or a pointer is exactly what you want to use here.

std::list<int>& list = a->list_;

or

std::list<int>* pList = &a->list_;

Using either the pointer or reference means that additions via a->list_.push_back( ... ) or pList->push_back( ... ) will be identical operations on the same collection.

Upvotes: 3

Matt
Matt

Reputation: 7160

Use a reference?

std::string a("This is a test");

std::string& b = a;

b[4] = 'L';

std::cout << a << std::endl << b << std::endl;

Here the & makes b a reference, so you'll see that both strings are changed by changing b.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258618

Yes, like so:

std::list<int>& my_list = a->list_;

Upvotes: 2

Constantinius
Constantinius

Reputation: 35059

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.

Upvotes: 7

Related Questions