is& * vector :: end()undefined behavior? [英] Is &*vector::end() undefined behavior?

查看:194
本文介绍了is& * vector :: end()undefined behavior?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为& * vector :: end()是未定义的行为...,直到我看到某篇文章请参阅 Stroustrup的代码

  void vector_pointer_test(element_t * first,element_t * last,int number_of_times)
{
vector< element_t>容器(第一,最后);
//& * container.begin()获取第一个元素的指针
sort(& * container.begin(),& * container.end());
unique(& * container.begin(),& * container.end());
}

解除引用 end() iterator undefined behavior,或者它是否有效?

解决方案

这是未定义的行为。也就是说,行为不是由C ++标准定义的。它可以由实现来定义。在这种情况下,如果迭代器是一个原始指针,编译器可能会优化&< / b>。在某些情况下, * i进入无操作,所以它可能工作。 Stroustrup可能已经知道他的向量使用原始指针作为迭代器。



即使编译器没有优化它,在实践中,它只有失败,如果向量的内存恰好被分配为在段边界处结束。 (或者如果迭代器实现被写为检查是不可解引用的,例如为了调试目的。)



在C ++ 11中, p>

  sort(container.data(),container.data()+ container.size()); 


I thought &*vector::end() was undefined behavior... until I saw some post refer to Stroustrup's code:

void vector_pointer_test(element_t* first, element_t* last, int number_of_times) 
{ 
       vector<element_t> container(first, last); 
       // &*container.begin() gets us a pointer to the first element 
       sort(&*container.begin(), &*container.end()); 
       unique(&*container.begin(), &*container.end()); 
}

Is dereferencing an end() iterator undefined behavior, or is it valid?

解决方案

It's undefined behaviour. That is, behaviour not defined by the C++ standard. It may be defined by the implementation. More likely, it will happen to work by chance in some situations and not others.

In this case, if the iterator is a raw pointer the compiler will likely optimise &*i into a no-op, so it will likely work. Stroustrup may have known his vector used raw pointers as iterators.

Even if the compiler doesn't optimise it away, in practice, it's only likely to fail if the vector's memory happens to be allocated to end at a segment boundary. (Or if the iterator implementation is written to check for being non-dereferenceable, eg for debugging purposes.)

In C++11 this should be written as:

sort(container.data(), container.data()+container.size()); 

这篇关于is&amp; * vector :: end()undefined behavior?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆