开发者

Invalid initialization error

开发者 https://www.devze.com 2023-02-17 18:52 出处:网络
I have a class with a private member std::set<Segment*> mSegments and the following method: st开发者_JS百科d::pair<iterator, iterator> getSegments() {

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

st开发者_JS百科d::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?


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!


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


boost::tie's parameters are non-const references, but begin and end return temporaries. You'd need to store them somewhere for that to work.


This is declaration of tie:

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

And this is declaration of begin (end):

iterator begin()

This means that begin() returns temporary object (not reference to it) which can't passed to tie.

0

精彩评论

暂无评论...
验证码 换一张
取 消