const reference error

Hey guys. I am looping through a list of objects and returning a constant reference to an object meeting some condition... but I am getting the following error:


1>error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const T' (or there is no acceptable conversion)


My code is as follows and the error is specified on the line marked with a comment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool getObject( const T& t_out ) const
{
    for( auto it = tList.cbegin(); it != tList.cend(); ++it )
    {
        const T& t = *it;
        if( t.meetsSomeCondition() )
        {
            t_out = t; // This is the error line
            return true;
        }

    }

    return false;
}

Where tList is:
 
QList<T> tList;



I can fix the error by removing the const-ness but I want to understand what is going wrong here, rather than bludgeoning my way through the build error.

Kind regards, aatwo.
you declared t_out as a constant
a constant cannot be modified
you try to modify t_out at line 8
Thanks for the reply.

So the confusion for me is that I've always been taught to read the type backwards, so in this case t_out would be a reference to a constant T object. In my head, when described like that, it makes sense that I should be allowed to set the reference to something else as long as the reference type is also a constant T object. It seems I miss-understood the role of const in this case.

Thank you for clearing that up for me.
I think you misunderstood the meaning of &.
It says if you work with the parameter passed to your function or with a copy of it.
In this case you are saying that you won't make a copy, and that you will treat the parameter as if it were a constant.


Your function looks like a find_if http://www.cplusplus.com/reference/algorithm/find_if/
perhaps you should consider to return an iterator or a pointer.
Last edited on
Topic archived. No new replies allowed.