Below, I have a class Container that contains a vector. The vector
contains pointers to a Base class. When the Container destructor is
called, I would like to delete all the objects that the pointers in the
vector are pointing to.
It works fine, IF I comment out the destructors in Base and Inherited.
If I leave the explicit destructors in there, it seg faults. Why is
there a difference?
Thanks,
Joe
#include <iostream>
#include <vector>
using namespace std;
struct Base {
virtual ~Base() {}
};
struct Inherited : public Base {
~Inherited() {}
};
class Container
{
public:
vector<Base*> v;
~Container()
{
// Need to delete pointed-to objects in v
for (vector<Base*>: :iterator i = v.begin();
i != v.end();
++i)
{
cout << "Deleting " << *i << endl;
delete *i;
}
}
};
int main()
{
Container c;
Inherited *f = new Inherited();
// Adding two pointers to the same object to Container
c.v.push_back(f );
c.v.push_back(f );
return 0;
} 7 3116 jo*******@gmail .com wrote: Below, I have a class Container that contains a vector. The vector contains pointers to a Base class. When the Container destructor is called, I would like to delete all the objects that the pointers in the vector are pointing to.
It works fine, IF I comment out the destructors in Base and Inherited. If I leave the explicit destructors in there, it seg faults. Why is there a difference?
None whatsoever. Your program produces undefined behaviour in both
cases. See below.
Thanks, Joe #include <iostream> #include <vector>
using namespace std;
struct Base { virtual ~Base() {} };
struct Inherited : public Base { ~Inherited() {} };
class Container { public: vector<Base*> v;
~Container() { // Need to delete pointed-to objects in v for (vector<Base*>: :iterator i = v.begin(); i != v.end(); ++i) { cout << "Deleting " << *i << endl; delete *i; } } };
int main() { Container c;
Inherited *f = new Inherited();
// Adding two pointers to the same object to Container c.v.push_back(f ); c.v.push_back(f );
How many pointers to the _same_ object does 'c.v' now contain? How
many times will you attempt to delete that object? return 0; }
V
Victor Bazarov wrote: jo*******@gmail .com wrote: Below, I have a class Container that contains a vector. The vector contains pointers to a Base class. When the Container destructor
is called, I would like to delete all the objects that the pointers in
the vector are pointing to.
It works fine, IF I comment out the destructors in Base and
Inherited. If I leave the explicit destructors in there, it seg faults. Why
is there a difference?
None whatsoever. Your program produces undefined behaviour in both cases. See below.
Thanks, Joe #include <iostream> #include <vector>
using namespace std;
struct Base { virtual ~Base() {} };
struct Inherited : public Base { ~Inherited() {} };
class Container { public: vector<Base*> v;
~Container() { // Need to delete pointed-to objects in v for (vector<Base*>: :iterator i = v.begin(); i != v.end(); ++i) { cout << "Deleting " << *i << endl; delete *i; } } };
int main() { Container c;
Inherited *f = new Inherited();
// Adding two pointers to the same object to Container c.v.push_back(f ); c.v.push_back(f );
How many pointers to the _same_ object does 'c.v' now contain? How many times will you attempt to delete that object?
c.v has two pointers to the same object. I try to delete the object
twice.
I agree, bad thing, but was wondering why it seemed to work without
explicit destructors.
Is there a way to tell whether or not a pointed-to object has been
deleted? return 0; }
V
You can actually avoid similar problems if you use std::auto_ptr
whenever the ownership
of a pointer changes.
And of course you'll need a copy constructor and assignment operator as
well
(or prevent them as shown below).
#include <memory>
class Container {
public:
// ...
void push_back(std:: auto_ptr<Base*> base) {
v.push_back(bas e.release(); }
private:
// prevent copying: not implemented:
Containter(cons t Container&);
// prevent assignment: not implemented:
Container& operator=(const Container&);
private:
vector<Base*> v;
};
Alternatively boost provides boost::shared_p tr.
Regards,
Stephan Brönnimann br****@osb-systems.com http://www.osb-systems.com
Open source rating and billing engine for
communication networks.
<jo*******@gmai l.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. . Victor Bazarov wrote: jo*******@gmail .com wrote:
<snip> Is there a way to tell whether or not a pointed-to object has been deleted?
Do a search on Smartpointers. They are good for this kind of thing, by
doing reference counting, or by integrating smartpointers with the delete
operator.
PKH
Jonathan Mcdougall wrote: jo*******@gmail .com wrote: Below, I have a class Container that contains a vector. The vector contains pointers to a Base class. When the Container destructor is called, I would like to delete all the objects that the pointers in the vector are pointing to.
/.../
For your specific case, since you have a container of pointers which you must delete, I would use a std::set, which allows no duplicates. That will prevent such misusage.
Unless, of course, the OP wants/needs (for whatever reason) to allow
mutiple pointers to the same object. In which case some kind of
reference counting (smart pointer?) is probably the way to go.
--
Lionel B
<jo*******@gmai l.com> wrote in message news:11******** *************@z 14g2000cwz.goog legroups.com... Below, I have a class Container that contains a vector. The vector contains pointers to a Base class. When the Container destructor is called, I would like to delete all the objects that the pointers in the vector are pointing to.
It works fine, IF I comment out the destructors in Base and Inherited. If I leave the explicit destructors in there, it seg faults. Why is there a difference?
What if you call clear() on the vector after the delete and
before pushing back more pointers?
How about one of the boost smart pointers? al******@hotmai l.com wrote: Is there a way to tell whether or not a pointed-to object has been
deleted?
You could maintain a set of deleted pointers and use this to ensure that you don't call delete with the same pointer twice.
That's also undefined behavior. You're not allowed to use the
value of a deleted pointer. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: christopher diggins |
last post by:
What I am trying to answer is, what the most prominent motivation for
implenting and using smart pointers in C++ is. Is it primarily to reduce
bugs resulting from memory access errors or primarily to permit lazy
deallocation designs (i.e. designs that rely on non-determined non-fixed
non-explicit deallocation of memory)? Obviously both are advantages, but I
want to know if programmers are finding that lazy deallocation is one of the
major...
|
by: mosfets |
last post by:
Hi,
I'm having a little trouble figuring out the difference in terms of
memory allocation between:
class person_info;
class A {
private:
|
by: Dr. J.K. Becker |
last post by:
Hi all,
I have vectors that holds pointers to other vectors, like so:
vector<whatever> x;
vector<whatever*> z;
z=&x;
Now I add something to x
|
by: Matthias Kaeppler |
last post by:
Hi,
in my program, I have to sort containers of objects which can be 2000
items big in some cases. Since STL containers are based around copying
and since I need to sort these containers quite frequently, I thought
it'd be a better idea to manage additional containers which are
initialized with pointers to the objects in the primary containers and
sort those (only pointers have to be copied around then).
However, that also means if I...
|
by: Takeshi |
last post by:
I have code as ff:
typedef double* (*DBLPTRFUNCPTR)(int) ;
typedef int* (*INTPTRFUNCPTR)(int) ;
typedef double (*DBLFUNCPTR)(int) ;
typedef int (*INTFUNCPTR)(int) ;
etc ....
typedef struct
| |
by: Akhil |
last post by:
How much is Pointers different in C# compared to C++?
Do we have destructors in C#? if yes, for what do we use it?
--
Cheers,
Akhil
|
by: madhu |
last post by:
http://msdn2.microsoft.com/en-us/library/fs5a18ce(VS.80).aspx
vector <intv1;
v1.push_back( 10 ); //adds 10 to the tail
v1.push_back( 20 ); //adds 20 to the tail
cout << "The size of v1 is " << v1.size( ) << endl;
v1.clear( ); //clears the vector
I have a few questions:
|
by: nabh4u |
last post by:
Hi,
I have a problem referencing to Vectors using pointers i.e. I am not able to use "call by reference" on vector variables.
I have a "read()" function in "x.cpp" and "main()" in "y.cpp". I have 3 vector variables in Main(). I want the read function to read the values into the vector using the address I send of the vectors..
Sample code:
//x.cpp
void read(vector <int> a,vector <int> b,vector < vector <int> > c)
|
by: smp |
last post by:
Does anyone know why making a vector of pointers is so much less efficient
than a vector of objects? For a simple example:
int num = 20;
vector<int*v_int_ptr;
v_int_ptr.reserve(num);
for(int i = 0; i < num; i++)
{
int* my_int_ptr = new int;
|
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...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
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...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
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
| |
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...
| | |