Invalid initialization error

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:

incorrect initialization of a non-constant link like std::_Rb_tree_const_iterator<Segment*>& from the temporary type std::_Rb_tree_const_iterator<Segment*>

I am not sure how to solve this problem. Can someone tell me what the problem is?

+4
source share
4 answers

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

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

Because of this, tie always accepts its parameters using the << 27> link so that they can be mutated. In your case, the return values ​​of begin() and end() are temporary, so they cannot be bound to non- const links.

make_pair (and make_tuple ), on the other hand, are designed to accept multiple values ​​and pack them into a single pair or tuple object that can be passed. 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!

+5
source

I don’t have much experience with boost::tie , but looking at the error message, I can say that the error is due to the fact that you are trying to bind a temporary link to an non-constant link.

Temporary users cannot bind to links to non-constant objects.

for instance

  Myclass &ref = Myclass(); // ill formed 
+3
source

boost::tie parameters are non-constant references, but begin and end return temporary. You will need to store them somewhere for this.

0
source

This is a link ad:

 template <class A, class B> tied<A,B> tie(A& a, B& b); 

And this announcement is the beginning (end):

 iterator begin() 

This means that begin () returns a temporary object (not a reference to it) that cannot be passed in for binding.

0
source

Source: https://habr.com/ru/post/1344431/


All Articles