Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid initialization error

Tags:

c++

iterator

I have a class with a private member std::set<Segment*> mSegments and the following method:

std::pair<iterator, iterator> getSegments() {
    return boost::tie(mSegments.begin(), mSegments.end());
}

and I get the following error:

invalid initialization of non-const reference of type std::_Rb_tree_const_iterator<Segment*>& from a temporary of type std::_Rb_tree_const_iterator<Segment*>

I'm not sure how to solve this one. Can anyone tell me what the problem is?

like image 843
Amir Rachum Avatar asked Feb 24 '23 18:02

Amir Rachum


2 Answers

I think that your problem is that you should probably be using make_pair here instead of tie. The point of tie is to allow functions that return tuples to have the return value assigned to multiple values at once. For example, if Get3DPoint returns a tuple<int, int, int>, then you could write

int x, y, z;
tie(x, y, z) = Get3DPoint();

Because of this, tie always accepts its parameters by non-constreference so that they can be mutated. In your case, the return values of begin() and end() are temporaries, so they can't be bound to non-const references.

make_pair (and make_tuple), on the other hand, are designed to take multiple values and package them up into a single pair or tuple object that can be passed around. This is what you want to use in your function. If you change the code to read

std::pair<iterator, iterator> getSegments() {
    return std::make_pair(mSegments.begin(), mSegments.end());
}

Then your code should compile just fine.

Hope this helps!

like image 118
templatetypedef Avatar answered Mar 08 '23 02:03

templatetypedef


I don't have much experience with boost::tie but by looking at the error message I can say that the error is because you are trying to bind a temporary to a non-const reference.

Temporaries cannot be bound to references to non-const objects.

For example

 Myclass &ref = Myclass(); // ill formed
like image 32
Prasoon Saurav Avatar answered Mar 08 '23 00:03

Prasoon Saurav