什么是常量的“const T& operator [](size_type i)”?

时间:2011-11-24 00:27:05

标签: c++ operator-overloading

我发现了这个有趣的一行:一本书http://www.acceleratedcpp.com/ - 来源 - 第11章 - Vec.h(我是std :: vector翻拍)

我真的不明白这个版本的运营商有什么用。为什么要定义此运算符的两个版本(const和非const)?

我甚至尝试过,在我看来,非const版本一直被调用... 你能解释一下吗?

#include <iostream>
#include <algorithm>
#include <cstddef>
#include <memory>
using namespace std;

template <class T> class Vec {
public:
    typedef T* iterator;
    typedef const T* const_iterator;
    typedef size_t size_type;
    typedef T value_type;
    typedef T& reference;
    typedef const T& const_reference;

    Vec() { create(); }
    explicit Vec(size_type n, const T& t = T()) { create(n, t); }

    Vec(const Vec& v) { create(v.begin(), v.end()); }
    Vec& operator=(const Vec&); // as defined in 11.3.2/196
    ~Vec() { uncreate(); }

    T& operator[](size_type i) { cout << "T&";return data[i]; }
    const T& operator[](size_type i) const { cout << "const T&!";return data[i]; }

    void push_back(const T& t) {
        if (avail == limit)
            grow();
        unchecked_append(t);
    }

    size_type size() const { return avail - data; }  // changed

    iterator begin() { return data; }
    const_iterator begin() const { return data; }

    iterator end() { return avail; }                 // changed
    const_iterator end() const { return avail; }     // changed
    void clear() { uncreate(); }
    bool empty() const { return data == avail; }

private:
    iterator data;  // first element in the `Vec'
    iterator avail; // (one past) the last element in the `Vec'
    iterator limit; // (one past) the allocated memory

    // facilities for memory allocation
    std::allocator<T> alloc;    // object to handle memory allocation

    // allocate and initialize the underlying array
    void create();
    void create(size_type, const T&);
    void create(const_iterator, const_iterator);

    // destroy the elements in the array and free the memory
    void uncreate();

    // support functions for `push_back'
    void grow();
    void unchecked_append(const T&);
};

template <class T> void Vec<T>::create()
{
    data = avail = limit = 0;
}

template <class T> void Vec<T>::create(size_type n, const T& val)
{
#ifdef _MSC_VER
    data = alloc.allocate(n, 0);
#else
    data = alloc.allocate(n);
#endif
    limit = avail = data + n;
    std::uninitialized_fill(data, limit, val);
}

template <class T>
void Vec<T>::create(const_iterator i, const_iterator j)
{
#ifdef _MSC_VER
    data = alloc.allocate(j - i, 0);
#else
    data = alloc.allocate(j - i);
#endif
    limit = avail = std::uninitialized_copy(i, j, data);
}

template <class T> void Vec<T>::uncreate()
{
    if (data) {
        // destroy (in reverse order) the elements that were constructed
        iterator it = avail;
        while (it != data)
            alloc.destroy(--it);

        // return all the space that was allocated
        alloc.deallocate(data, limit - data);
    }
    // reset pointers to indicate that the `Vec' is empty again
    data = limit = avail = 0;

}

template <class T> void Vec<T>::grow()
{
    // when growing, allocate twice as much space as currently in use
    size_type new_size = max(2 * (limit - data), ptrdiff_t(1));

    // allocate new space and copy existing elements to the new space
#ifdef _MSC_VER
    iterator new_data = alloc.allocate(new_size, 0);
#else
    iterator new_data = alloc.allocate(new_size);
#endif
    iterator new_avail = std::uninitialized_copy(data, avail, new_data);

    // return the old space
    uncreate();

    // reset pointers to point to the newly allocated space
    data = new_data;
    avail = new_avail;
    limit = data + new_size;
}

// assumes `avail' points at allocated, but uninitialized space
template <class T> void Vec<T>::unchecked_append(const T& val)
{
    alloc.construct(avail++, val);
}

template <class T>
Vec<T>& Vec<T>::operator=(const Vec& rhs)
{
    // check for self-assignment
    if (&rhs != this) {

        // free the array in the left-hand side
        uncreate();

        // copy elements from the right-hand to the left-hand side
        create(rhs.begin(), rhs.end());
    }
    return *this;
}

int main() {
    Vec<int> v;
    v.push_back(5);


    cout << v[0] << endl; // even now the non-const version is called!

    system("pause");
}

谢谢!

2 个答案:

答案 0 :(得分:11)

很可能那是

 const T& operator[](size_type i) const // <-- note the extra const

Const向编译器发出信号,告知调用代码可以修改返回值

这与:

有关
    如果引用可以修改,
  • 通过引用返回将是不安全的
  • 通过引用返回可以比按值返回更有效
  • 无法在 const对象上调用非const方法 (实例)
  

基本原理:如果声明对象本身为const,则该方法无法返回对成员non-const(的一部分)的引用;如果你愿意,那么级联:这就是所谓的 const-correctness

在实践中,您经常会看到const / non-const重载,如下所示:

class Container
{
    private: 
       int data[10];
    public:
       int       & operator[](int i)       { return data[i]; }
       int const & operator[](int i) const { return data[i]; }
};

//
Container x;
Container& r = x;
const Container& cr = x;

x [3] += 1;
r [3] += 1;  // just fine, non-const overload selected
cr[3] += 1;  // compile error, return value `const &`

相关主题:

  • 对于鲜为人知的volatile修饰符
  • ,情况大致相同
  • const的相关关键字(反之,如果您愿意)为 mutable

答案 1 :(得分:1)

C ++允许重载仅在constness上不同的成员函数。你问题中的两个成员函数是:

T& operator[](size_type i);
const T& operator[](size_type i) const;

当您拥有类型为Vec的非const对象时,将调用第一个索引运算符。当你有一个类型为Vec的const对象时,会调用第二个。如果您没有第二个成员函数,尝试使用索引运算符作为const Vec的变量将导致编译时错误。

在您的示例中,尝试在设置main后将以下内容添加到v以查看会发生什么。

const Vec<int> v2(v);
cout << v2[0] << endl;