當我試圖在C++中使用Python實現可迭代對象時(使用boost :: python),我遇到了一個奇怪的問題。 Python似乎總是提前引用一個元素,因此,它跳過了第一個元素,並且還引用了「end」元素。我也沒有信心,如果我的返回值策略選擇正確,但它是唯一一個似乎正常工作,如果我用std :: string作爲元素類型替換int。迭代器標籤被故意選擇 - 我打算實現可迭代對象來訪問只能遍歷一次的資源。爲什麼boost :: python迭代器跳過第一個元素?
C++代碼:
#include <Python.h>
#include <boost/python.hpp>
#include <iostream>
#include <iterator>
int nextInstance{0};
class Foo
{
public:
class iterator : public std::iterator<std::input_iterator_tag, int>
{
public:
iterator() = delete;
iterator& operator=(const iterator&) = delete;
iterator(const iterator& other)
:
instance_(nextInstance++),
pos_(other.pos_)
{
std::cout << instance_ << " copy ctor " << other.instance_ << " (" << pos_ << ")\n";
}
explicit iterator(int pos)
:
instance_(nextInstance++),
pos_(pos)
{
std::cout << instance_ << " ctor (" << pos_ << ")\n";
}
bool operator==(iterator& other)
{
std::cout << instance_ << " operator== " << other.instance_ << " (" << pos_ << ", " << other.pos_ << ")\n";
return pos_ == other.pos_;
}
int& operator*()
{
std::cout << instance_ << " operator* (" << pos_ << ")\n";
return pos_;
}
iterator operator++(int)
{
++pos_;
std::cout << instance_ << " operator++ (" << pos_ << ")\n";
return *this;
}
~iterator()
{
std::cout << instance_ << " dtor\n";
}
private:
const int instance_;
int pos_{0};
};
iterator begin()
{
std::cout << "begin()\n";
return iterator(0);
}
iterator end()
{
std::cout << "end()\n";
return iterator(3);
}
};
BOOST_PYTHON_MODULE(pythonIterator)
{
boost::python::class_<Foo, boost::noncopyable>("Foo", boost::python::init<>())
.def("__iter__", boost::python::iterator<Foo, boost::python::return_value_policy<boost::python::copy_non_const_reference>>{});
}
Python代碼:
#!/usr/bin/python
import pythonIterator
foo = pythonIterator.Foo()
for i in foo:
print i
輸出:
end()
0 ctor (3)
begin()
1 ctor (0)
2 copy ctor 1 (0)
3 copy ctor 0 (3)
1 dtor
0 dtor
4 copy ctor 2 (0)
5 copy ctor 3 (3)
3 dtor
2 dtor
4 operator== 5 (0, 3)
4 operator++ (1)
6 copy ctor 4 (1)
6 operator* (1)
6 dtor
1
4 operator== 5 (1, 3)
4 operator++ (2)
7 copy ctor 4 (2)
7 operator* (2)
7 dtor
2
4 operator== 5 (2, 3)
4 operator++ (3)
8 copy ctor 4 (3)
8 operator* (3)
8 dtor
3
4 operator== 5 (3, 3)
5 dtor
4 dtor
謝謝。如果有人感興趣爲什麼後增量(不是預增量)在這裏 - 這是boost :: python迭代器包裝器所需的。 – kpx1894 2015-02-11 22:34:42