473,698 Members | 1,888 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dangling references?

Hi,

I have a question regarding references, and their chance to "dangle" (if
that's possible at all):

Say I have a collection ob objects, and I take a reference to one of
them. Now I sort this collection, or invoke whatever action it takes to
copy around the elements in the collection.
What happens to the reference?

Example:

class A {};

int main()
{
list<A> coll;
// ... add elements to coll

A &ref = *(coll.begin()) ;
coll.sort(); // assume that referenced element gets copied around

// at this point, is 'ref' dangling or is it still valid?
}
Oct 10 '05 #1
6 2093
Matthias Kaeppler wrote:
I have a question regarding references, and their chance to "dangle" (if
that's possible at all):
It is entirely possible.

int *pint = new int(42);
int &r = *pint; // r is now a reference to a dynamic object of type int
delete pint;
// r is now "dangling"

I can set 'pint' to 0 to indicate that it's not pointing to anything, but
there is no way to do this with 'r'.
Say I have a collection ob objects, and I take a reference to one of
them. Now I sort this collection, or invoke whatever action it takes to
copy around the elements in the collection.
What happens to the reference?
It depends on the collection and what is done to the elements when they
are sorted.
Example:

class A {};

int main()
{
list<A> coll;
// ... add elements to coll

A &ref = *(coll.begin()) ;
coll.sort(); // assume that referenced element gets copied around

// at this point, is 'ref' dangling or is it still valid?
}


The Standard actually doesn't specify _how_ elements' values are exchanged
but I'll venture a guess that 'swap' is used. And the Standard requires
that 'swap' does not invalidate references. YMMV, of course. I'd ask in
comp.std.c++ for clarification, they know legalese and can explain why the
Standard is so vague re sorting of a list.

V
Oct 10 '05 #2
Matthias Kaeppler wrote:
Hi,

I have a question regarding references, and their chance to "dangle" (if
that's possible at all):

Say I have a collection ob objects, and I take a reference to one of
them. Now I sort this collection, or invoke whatever action it takes to
copy around the elements in the collection.
What happens to the reference?

Example:

class A {};

int main()
{
list<A> coll;
// ... add elements to coll

A &ref = *(coll.begin()) ;
coll.sort(); // assume that referenced element gets copied around


a) Iterators remain valid. The standard is silent about references [I
think].

b) However, depending on how the sorting is done, you may or may not find
the smallest element. You should not assume that the values of the list
elements change. The list container is somewhat special in that the
standard allows for sort to just rearrange the pointers without actually
shuffling the nodes around:

#include <list>
#include <iostream>
#include <cstdlib>

int main() {
std::list<unsig ned long> coll;
for ( unsigned long i = 0; i < 10; ++i ) {
coll.push_front ( i );
}

std::list< unsigned long >::iterator iter = coll.begin();
std::cout << "reference value: " << *iter << '\n';
coll.sort();
std::cout << "reference value: " << *iter << '\n';
std::cout << "lowest value: " << *(coll.begin()) << '\n';
}
prints on my machine:

reference value: 9
reference value: 9
lowest value: 0

If you use a reference instead of an iterator, I would expect the result to
be the same.
Best

Kai-Uwe Bux
Oct 10 '05 #3
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:tv******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...
The Standard actually doesn't specify _how_ elements' values are exchanged
but I'll venture a guess that 'swap' is used. And the Standard requires
that 'swap' does not invalidate references. YMMV, of course. I'd ask in
comp.std.c++ for clarification, they know legalese and can explain why the
Standard is so vague re sorting of a list.


Nothing is said about invalidating iterators (but also not of not
invalidating them). For other items, such as splice or erase, iterator
invalidation is explicitly mentioned, so the converse would be implicit?
Therefore I think you ought to be able to assume the iterator still points
to the beginning of the list, and so the reference is also still valid (but
possibly refering to a different actual item). But indeed it is rather
vague... tho it implies that when iterators are not invalidated the sort
must be done in-place, which is a good space requirement.

Ferdi
Oct 10 '05 #4
Ferdi Smit wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:tv******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...
The Standard actually doesn't specify _how_ elements' values are
exchanged
but I'll venture a guess that 'swap' is used. And the Standard requires
that 'swap' does not invalidate references. YMMV, of course. I'd ask in
comp.std.c++ for clarification, they know legalese and can explain why
the Standard is so vague re sorting of a list.


Nothing is said about invalidating iterators (but also not of not
invalidating them). For other items, such as splice or erase, iterator
invalidation is explicitly mentioned, so the converse would be implicit?
Therefore I think you ought to be able to assume the iterator still points
to the beginning of the list, and so the reference is also still valid
(but possibly refering to a different actual item). But indeed it is
rather vague... tho it implies that when iterators are not invalidated the
sort must be done in-place, which is a good space requirement.

Ferdi


From 23.1/11:

Unless otherwise specified (either explicitly or by defining a function in
terms of other functions), invoking a container member function or passing
a container as an argument to a library function shall not invalidate
iterators to, or change the values of, objects within that container.
So, yes, it is implicit. However, there is a little catch. If you say

typedef std::list<T> T_List;
T_list the_list;
// fill the list
...
T_list::const_i terator front_iter = the_list.begin( );
the_list.sort() ;
assert( front_iter == the_list.begin( ) );

you may find that the assertion fails: the iterator is not invalidated, but
that the_list.begin( ) returns a different value now. The member function
the_list.sort() is allowed to just redirect pointers and not shuffle around
the actual data.
Best

Kai-Uwe Bux
Oct 10 '05 #5
On Mon, 10 Oct 2005 17:10:34 -0400, Kai-Uwe Bux wrote:
From 23.1/11:

Unless otherwise specified (either explicitly or by defining a function in
terms of other functions), invoking a container member function or passing
a container as an argument to a library function shall not invalidate
iterators to, or change the values of, objects within that container.
So, yes, it is implicit. However, there is a little catch. If you say

typedef std::list<T> T_List;
T_list the_list;
// fill the list
...
T_list::const_i terator front_iter = the_list.begin( );
the_list.sort() ;
assert( front_iter == the_list.begin( ) );

you may find that the assertion fails: the iterator is not invalidated, but
that the_list.begin( ) returns a different value now. The member function
the_list.sort() is allowed to just redirect pointers and not shuffle around
the actual data.


Ok, I missed that issue; you're right of course. But considering this,
what does it actually mean when iterators are not invalidated when they
can a) point to any item in b) any location in the list. Ie. they are as
good as random. The only guarantee is them pointing in the list... not
very useful.
Oct 11 '05 #6
Kai-Uwe Bux wrote:
Ferdi Smit wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:tv******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...
The Standard actually doesn't specify _how_ elements' values are
exchanged
but I'll venture a guess that 'swap' is used. And the Standard requires
that 'swap' does not invalidate references. YMMV, of course. I'd ask in
comp.std.c++ for clarification, they know legalese and can explain why
the Standard is so vague re sorting of a list.


Nothing is said about invalidating iterators (but also not of not
invalidating them). For other items, such as splice or erase, iterator
invalidation is explicitly mentioned, so the converse would be implicit?
Therefore I think you ought to be able to assume the iterator still points
to the beginning of the list, and so the reference is also still valid
(but possibly refering to a different actual item). But indeed it is
rather vague... tho it implies that when iterators are not invalidated the
sort must be done in-place, which is a good space requirement.

Ferdi


From 23.1/11:

Unless otherwise specified (either explicitly or by defining a function in
terms of other functions), invoking a container member function or passing
a container as an argument to a library function shall not invalidate
iterators to, or change the values of, objects within that container.
So, yes, it is implicit. However, there is a little catch. If you say

typedef std::list<T> T_List;
T_list the_list;
// fill the list
...
T_list::const_i terator front_iter = the_list.begin( );
the_list.sort() ;
assert( front_iter == the_list.begin( ) );

you may find that the assertion fails: the iterator is not invalidated, but
that the_list.begin( ) returns a different value now. The member function
the_list.sort() is allowed to just redirect pointers and not shuffle around
the actual data.


The important point about list::sort is that front_iter (and every
other iterator in list) will still reference the same element in
the_list after the list has been sorted - even though that element's
position in the the_list may have changed. As a consequence, any code
in possession of an iterator in the_list will not suddenly find
themselves with an iterator to some other element just because the
the_list has been sorted. In other words, calling list::sort
invalidates none of the the_list's iterators, it invalidates only
properties of the_list itself. std::sort on the other hand provides the
opposite behavior: it invalidates the iterators it sorts while
preserving the properties of their container.

If

assert( front_iter == the_list.begin( ) );

really has to be true after the_list has been sorted, than std::sort()
and not list::sort() should be called to sort the_list - although it's
hard to imagine the circumstances in which this assertion would make
sense. Since one of the primary advantages of std::list is the
constancy of its iterators, calling list::sort() instead of std::sort()
is usually the right way to sort std::list elements.

Greg

Oct 11 '05 #7

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

Similar topics

13
3085
by: Aravind | last post by:
I would like to know in what manner dangling pointers affect the security of a application developed using C++.What are the loopholes that are created by dangling pointers and how they could be exploited by hackers?. Aravind
6
1955
by: Tony Johansson | last post by:
Hello Experts! I'm reading in a book about C++ and the book says common errors is "A function should not return a constant references to its parameter passed by constant references" Why? Here I have written a method that has exactly this which is the parameter is passed by constant references and I return constant references what is it that can cause common error by writng in this way.
20
6556
by: __PPS__ | last post by:
Hello everybody in a quiz I had a question about dangling pointer: "What a dangling pointer is and the danger of using it" My answer was: "dangling pointer is a pointer that points to some area of ram that's not reserved by the program. Accessing memory through such pointer is likely to result in core dump (memory access violation)"
5
1973
by: Richard | last post by:
My experience has always been that you're SOL when trying to safely detect and stop references to dangling memory (non-null pointers to free'ed blocks) at runtime (C99, Linux). Maybe somebody clever has worked this out, though? (Apologies to those who find the question off topic for CUP or CLC)
1
4419
by: sekhar_ps | last post by:
if we store some value at the place in memory which void pointer references then we increment void pointer this leads to dangling pointer?can any one explain whats the reasons for dangling pointer
10
1746
by: Belebele | last post by:
Suppose that I have a method that returns references to "elements" in an iterator, and a method to advance the iterator: class Element { /* ... */ }; class Iterator { public: Element& operator*() const; Iterator& operator++();
1
2476
by: sridhard2406 | last post by:
Hi All, I have a doubt on undrestanding Dangling pointers.Below I mentioned sample code. please let me know, my view on Dangling pointers is correct or not? main( ) { char *a,*b,*c; a = (char *)malloc(40); b = a; c = b; free(a);
0
8672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9018
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...
1
8890
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8858
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
7711
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...
1
6517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4360
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...
1
3038
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
3
1997
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.