473,881 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

No out_of_range exception for "iterator + n" vs. vector.at( n )

Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range exception?
Maybe this is a gcc issue?

I'm using gcc version 3.3.3 (cygwin special).

Here's the full sample code:

#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

int main() {
vector<int> code;
code.push_back( 10L );
code.push_back( 20L );

vector<int>::it erator iter = code.begin();
try {
cout << *(iter + 5) << endl; // 0
cout << code.at( 10 ) << endl; // vector [] access out of range
} catch( out_of_range e ) {
cout << e.what() << endl;
}

return 0;
}
Thanks,
Mike

Jul 22 '05 #1
13 5092
"Mike Austin" <mi**@mike-austin.com> wrote in message
news:0L******** *************@b gtnsc04-news.ops.worldn et.att.net...
Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range exception?

Because that's the way the library is designed.
If you want range checking, use vector::at().
That's what it's for.

This follows the "don't pay for what you don't use"
principle of C++. ('at()' will necessarily add more
overhead which might be unacceptable for some
applications).
Maybe this is a gcc issue?
No.
I'm using gcc version 3.3.3 (cygwin special).

Here's the full sample code:

#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

int main() {
vector<int> code;
code.push_back( 10L );
code.push_back( 20L );

vector<int>::it erator iter = code.begin();
try {
cout << *(iter + 5) << endl; // 0
I don't know what you mean by your comment "0",
but note that this statement produces 'undefined behavior'.
cout << code.at( 10 ) << endl; // vector [] access out of range
} catch( out_of_range e ) {
cout << e.what() << endl;
}

return 0;
}


If you don't use the protection of 'vector::at()' you can still protect
yourself by checking e.g. 'vector::size() ', 'vector::empty( )', comparing
against 'vector::end()' , etc.

-Mike
Jul 22 '05 #2
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:s9******** *********@newsr ead3.news.pas.e arthlink.net...
try {
cout << *(iter + 5) << endl; // 0


Also note that you can use the possibly more intiutive
array notation with a vector:

iter[n]; /* but still no bounds checking */
-Mike
Jul 22 '05 #3

"Mike Austin" <mi**@mike-austin.com> wrote in message
news:0L******** *************@b gtnsc04-news.ops.worldn et.att.net...
Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range
exception?
Maybe this is a gcc issue?


Vector iterators are often implemented as pointers, i.e. something like

template <class T>
class vector
{
public:
typedef T* iterator;
typedef const T* const_iterator;

So vector iterators don't throw exceptions for the same reasons that
ordinary pointers don't.

john
Jul 22 '05 #4
Mike Austin wrote:
Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range exception?
It's never required to. It's undefined behavior to cause an iterator
to go outside the bounds of the array (with the exception of one past the
end).

cout << *(iter + 5) << endl; // 0
Evaluating expression (iter + 5) is undefined beahvior.
cout << code.at( 10 ) << endl; // vector [] access out of range


This is OK. At specifically throws an exception for out of range.
Jul 22 '05 #5

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2t******** *****@uni-berlin.de...

"Mike Austin" <mi**@mike-austin.com> wrote in message
news:0L******** *************@b gtnsc04-news.ops.worldn et.att.net...
Hi all. Just working on a small virtual machine, and thought about using vector iterators instead of pointer arithmetic. Question is, why does an iterator plus any number out of range not generate a out_of_range
exception?
Maybe this is a gcc issue?


Vector iterators are often implemented as pointers, i.e. something like

template <class T>
class vector
{
public:
typedef T* iterator;
typedef const T* const_iterator;

So vector iterators don't throw exceptions for the same reasons that
ordinary pointers don't.


That's possibly an 'incidental' reason for some implementations ,
but imo not "the" reason, which is to allow best possible performance
by not imposing bounds-check overhead.

-Mike
Jul 22 '05 #6
Mike Austin wrote:
Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range exception?
Maybe this is a gcc issue?

I'm using gcc version 3.3.3 (cygwin special).

Here's the full sample code:

#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

int main() {
vector<int> code;
code.push_back( 10L );
code.push_back( 20L );

vector<int>::it erator iter = code.begin();
try {
cout << *(iter + 5) << endl; // 0
cout << code.at( 10 ) << endl; // vector [] access out of range
} catch( out_of_range e ) {
cout << e.what() << endl;
}

return 0;
}

May well be wrong, but I belive only the member function at() will throw
an out_of_range, so you need to use that to test, otherwise the compiler
has not idea what you are doing.

Adrian
Jul 22 '05 #7
"Mike Austin" <mi**@mike-austin.com> wrote in message
news:0L******** *************@b gtnsc04-news.ops.worldn et.att.net...
Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range exception? Maybe this is a gcc issue?
Thanks for everyone's reply. The reason I ask is that I want to point to a
index into vector, then read an offset by that. I could use code.at( ip +
offset ), but I wanted to do everything with iterators. I realize [] does
no bounds checking, but did not know that (iter + n) does not either.

"iter + 0" is the selector
"iter + 1" is the first argument
etc.

Thanks,
Mike
I'm using gcc version 3.3.3 (cygwin special).

Here's the full sample code:

#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

int main() {
vector<int> code;
code.push_back( 10L );
code.push_back( 20L );

vector<int>::it erator iter = code.begin();
try {
cout << *(iter + 5) << endl; // 0
cout << code.at( 10 ) << endl; // vector [] access out of range
} catch( out_of_range e ) {
cout << e.what() << endl;
}

return 0;
}
Thanks,
Mike


Jul 22 '05 #8
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:s9******** *********@newsr ead3.news.pas.e arthlink.net...
"Mike Austin" <mi**@mike-austin.com> wrote in message
news:0L******** *************@b gtnsc04-news.ops.worldn et.att.net...
Hi all. Just working on a small virtual machine, and thought about using vector iterators instead of pointer arithmetic. Question is, why does an iterator plus any number out of range not generate a out_of_range

exception?

Because that's the way the library is designed.
If you want range checking, use vector::at().
That's what it's for.

This follows the "don't pay for what you don't use"
principle of C++. ('at()' will necessarily add more
overhead which might be unacceptable for some
applications).


Well, I don't like the way it works. I use vector so I don't have to worry
(as much) about my programs going awry.
I'd be delighted if you could help me write a "safe_itera tor" class. Here's
a start:

template <typename T>
class safe_iterator : public T::iterator {
Value operator ++() {
if( *this == container->end() ) // how to access "container" ?
throw out_of_range( "*** operator vector *(): out of range" );
}
};

Regards,
Mike

Jul 22 '05 #9
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:s9******** *********@newsr ead3.news.pas.e arthlink.net...
If you don't use the protection of 'vector::at()' you can still protect
yourself by [..snip..] comparing against 'vector::end()' , etc.


Note that it is not obvious to compare against end(), because it may
be too late to avoid Undefined Behavior (UB):
iter += 5; // if result is > vect.end(), UB happens here!
if( iter >= vect.end() ) { ... /* but it's too late */ ... };

hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
4878
by: gregory_may | last post by:
I have an application I created called "JpegViewer.exe". It simply loads a Jpeg file and displays in on the screen. It works great, in my lab. When I am using it at a customer site, things change. Occasionally, it blows up with an Application Exception. It seems to only die at the customer site
2
58204
by: Chris Herring | last post by:
Hi there: Well, let me start off by saying that I am a Visual Studio drag and drop weenie, not a real programmer. So I tend to get confused when things do not look like the instructions said they were going to look :) . Here is my current dilemma: I am having a strange problem with my ASP.NET application. I am building the application using Visual Basic .Net in Visual Studio.NET 2003. Lately, I have frequently been getting the following...
0
1592
by: Lionel B | last post by:
Greetings, Using gcc (GCC) 3.3.3 (cygwin special) on Win2K Does anyone know if there is a convenient mechanism to cause a C++ exception to be thrown whenever a IEEE 754 floating-point "exception" is raised? Currently I a check the FPU status word wherever I wish to test for FP errors and throw a C++ exception accordingly. This is fine; but
5
2707
by: Peter Steele | last post by:
We have an application that when it runs in the IDE in debug mode an unhandled exception is occurring in a system header file associated with STL stirngs. The actual statement that crashes is return ::memcmp(_First1, _First2, _Count); On inspecting these variables, the strings are in fact equal when the exception occurs and _Count is the right size. As a test I replaced this code in the system include file with a for loop to do the...
7
9548
by: Søren Dreijer | last post by:
Hi, I have a mixed C#, managed C++ and unmanaged C++ project. The managed class calls a method which exists in an unmanaged singleton class. During the entire lifetime of the application, this gives no problems whatsoever. However, upon shutdown an exception pops up: "The string binding is invalid" If I call the singleton method from inside a purely unmanaged class, I
4
2905
by: R.A.M. | last post by:
Hello, Could you help me plase? I have an ASP.NET page with "Search" button; when button is clicked Search_Click is called; here's the code: protected void Search_Click(object sender, EventArgs e) { Debug.WriteLine("WWWPage.Search_Click()"); ... try
1
3027
by: R.A.M. | last post by:
Hello, Could you help me plase? I am describing my problem second time because I haven't got a solution. I have an ASP.NET page with "Search" button; when button is clicked Search_Click is called; here's the code: protected void Search_Click(object sender, EventArgs e) { Debug.WriteLine("WWWPage.Search_Click()"); ...
2
24532
by: Abubakar | last post by:
Hi all, I'm writing an app in vc++ 2k5 (all native/unmanaged). This application does a lot of multithreading and socket programming. Its been months since I'm developing this application, at this point a lot of it is working just fine, my app running fine, threads r being made and destroyed, memory is being dynamically allocated at God knows how many places and ,hopefully, getting deallocated as well. Its just by coincedence I happened...
2
2865
by: dkmd_nielsen | last post by:
I have two rather simple class methods coded in Ruby...my own each iterator: The iterator is used internally within the class/namespace, and be available externally. That way I can keep everything hidden about the "instructions table." # Loop through each instruction in the block, yielding the result from # the specified code block. def each(&logic) @instructions.each {|instr| yield instr} end
0
9776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10716
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10399
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9552
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5780
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5976
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.