user3461957
user3461957

Reputation: 163

Converting variable reference to value?

I am using list from STL. To access I used l.front() or l.back(). Both of these methods return reference. I am copying content of one list into other so don't want reference. As the methods are returning references so I want to know that is there some other way by which I can convert reference to value? And I will just receive value not reference.

int main()
{

    list<int> l;
    l.push_back(2);
    l.push_back(5);
    l.push_back(7);
    l.push_back(9);

    while( ! l.empty() )
    {
        cout<<l.front()<<endl;
        l.pop_front();
    }

    list<int> l1;
    l1.push_back(10);
    l1.push_back(15);
    l1.push_back(30);


    l.push_back( l1.front() );   // here I need value not reference.


    system("pause");
    return 0;
}

Upvotes: 0

Views: 698

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

You will indeed get value

l.push_back( l1.front() );   // here I need value not reference

because the value referenced to by l1.front() will be used to create an element of list l. There is no any need to create any intermediate temporary object that only to get the target value.:)

try this simple example

#include <iostream>
#include <list>
#include <cstdlib>


int main()
{
    std::list<int> l;

    std::list<int> l1;

    l1.push_back( 10 );
    l1.push_back( 15 );
    l1.push_back( 30 );

    l.push_back( l1.front() );

    for ( int x : l1 ) std::cout << x << ' ';
    std::cout << std::endl;

    for ( int x : l ) std::cout << x << ' ';
    std::cout << std::endl;

    std::system( "pause" );

    return 0;
}

As you will see each list contains its own element with value 10.

Upvotes: 1

iavr
iavr

Reputation: 7637

Have a look at std::list::push_back. There are two versions taking different input arguments:

  1. const T& value: the new element is initialized as a copy of value.
  2. T&& value: value is moved into the new element

In your case, l1.front() is an lvalue reference T&, so version 1 is chosen and the value is copied, which is what you want.

Upvotes: 0

Related Questions