是 back_insert_iterator<>按值传递安全吗?
我有一个看起来像这样的代码:
struct Data { int value; };
class A {
public:
typedef std::deque<boost::shared_ptr<Data> > TList;
std::back_insert_iterator<TList> GetInserter()
{
return std::back_inserter(m_List);
}
private:
TList m_List;
};
class AA {
boost::scoped_ptr<A> m_a;
public:
AA() : m_a(new A()) {}
std::back_insert_iterator<A::TList> GetDataInserter()
{
return m_a->GetInserter();
}
};
class B {
template<class OutIt>
CopyInterestingDataTo(OutIt outIt)
{
// loop and check conditions for interesting data
// for every `it` in a Container<Data*>
// create a copy and store it
for( ... it = ..; .. ; ..) if (...) {
*outIt = OutIt::container_type::value_type(new Data(**it));
outIt++; // dummy
}
}
void func()
{
AA aa;
CopyInterestingDataTo(aa.GetDataInserter());
// aa.m_a->m_List is empty!
}
};
问题是,即使在调用 CopyInterestingDataTo()
后,A::m_List
也始终为空。但是,如果我调试并进入 CopyInterestingDataTo()
,迭代器确实会存储所谓插入的数据!
更新: 我找到了罪魁祸首。我实际上有这样的想法:
class AA {
boost::scoped_ptr<A> m_a;
std::back_insert_iterator<A::TList> GetDataInserter()
{
//return m_a->GetInserter(); // wrong
return m_A->GetInserter(); // this is the one I actually want
}
// ..... somewhere at the end of the file
boost::scoped_ptr<A> m_A;
};
现在,我应该将哪个答案标记为答案? 对于那些没有被选中的人真的很抱歉,但是你们肯定得到了一些赞成票:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短的回答是肯定的,
back_insert_iterator
可以安全地按值传递。长答案:来自标准 24.4.2/3:和24.1.2/1
最后来自 23.1 中的表 64:
编辑: 乍一看,您的代码对我来说没问题,您是否 100% 确定元素确实被插入?如果您是,我将单步执行代码并检查
aa.m_a->m_List
对象的地址,并将其与outIt
中存储的地址进行比较>CopyInterestingDataTo,如果它们不相同,则有些可疑。The short answer is yes,
back_insert_iterator
is safe to pass by value. The long answer: From standard 24.4.2/3:And 24.1.2/1
And finally from Table 64 in 23.1:
EDIT: At a glance your code looks OK to me, are you 100% certain that elements are actually being inserted? If you are I would single step through the code and check the address of the
aa.m_a->m_List
object and compare it to the one stored inoutIt
inCopyInterestingDataTo
, if they're not the same something's fishy.以下代码编译后打印“1”,表示已将一项添加到列表中:
The following code, which compiles, prints "1", indicating one item added to the list: