繁体   English   中英

std :: upper_bound返回const成员函数中的const迭代器

[英]std::upper_bound returns const iterator in const member function

这是一个包含某些structboost::circular_buffer的类。 我为迭代器创建了一个typedef到包含的circular_buffer

我的问题是:当doWork函数标记为const ,由于返回值为boost::cb_details::const_traits ,因此std::upper_bound的返回值与MyIterator类型不兼容。 如果我从函数中删除const关键字,我的所有编译错误都会消失。

要清楚编译器错误是这样的:

 error: conversion from 'boost::cb_details::iterator<boost::circular_buffer<Wrapper<int>::Sample, std::allocator<Wrapper<int>::Sample> >, boost::cb_details::const_traits<std::allocator<Wrapper<int>::Sample> > >' to non-scalar type 'Wrapper<int>::MyIterator {aka boost::cb_details::iterator<boost::circular_buffer<Wrapper<int>::Sample, std::allocator<Wrapper<int>::Sample> >, boost::cb_details::nonconst_traits<std::allocator<Wrapper<int>::Sample> > >}' requested [](const Sample& a, const Sample& b) { return a.foo < b.foo; }); 

这是一个独立的例子:

#include <algorithm>
#include <boost/circular_buffer.hpp>

template <typename T>
class Wrapper {
 public:
    struct Sample {
        T foo;
    };

    typedef typename boost::circular_buffer<Sample>::iterator MyIterator;

    Wrapper(int size) { cb.resize(size); }

    void add(T val) { cb.push_back(Sample{val}); }

    void doWork(T bound) const {
        MyIterator iter =
            std::upper_bound(cb.begin(), cb.end(), Sample{3},
                         [](const Sample& a, const Sample& b) { return a.foo < b.foo; });
    }

    boost::circular_buffer<Sample> cb;
};

int main() {
    Wrapper<int> buf(100);
    buf.add(1);
    buf.add(5);
    buf.doWork(3);
    return 0;
}

那么,为什么这个函数不能是const? 为什么标记为const会产生这种副作用? 我想在容器中使用非const迭代器,但在我的实际测试用例中,我并不打算实际修改容器。

你需要一个const_iterator ,因为你有效地观察了一个const容器。

也许:

typedef typename boost::circular_buffer<Sample>::const_iterator MyConstIterator;

...然后让iter其中之一。

有人会告诉你,你可以用auto来避免这种情况。 这是真的,但是你永远不会发现这个“bug”,或者const_iterator存在。

如果您的函数标记为const那么您对成员变量的所有访问权限也将是const

const容器只允许访问const_迭代器,这就是迭代器的工作方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM