473,732 Members | 2,214 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

best way to "delete" all objects in a std::vector.

I have std::vector<Bas e *bases;

I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);

Is it possible without writing an adapter? Is there a better way? Is
there an existing adapter?

Thanks,
Daniel.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity .net/wordpress/>
Jun 27 '08 #1
19 10755
On Jun 3, 2:23 pm, Daniel Pitts
<newsgroup.spam fil...@virtuali nfinity.netwrot e:
I have std::vector<Bas e *bases;

I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);

Is it possible without writing an adapter? Is there a better way? Is
there an existing adapter?
Keeping plain pointers to dynamic objects is way too much trouble.
Smart pointers is the best way. boost::shared_p tr is suitable:

#include <boost/shared_prt.hpp>
/* ... */
typedef boost::shared_p tr<BaseBasePtr;
std::vector<Bas ePtrbases;

This and other problems magically vanish...

Ali
Jun 27 '08 #2
On Jun 3, 5:23 pm, Daniel Pitts
<newsgroup.spam fil...@virtuali nfinity.netwrot e:
I have std::vector<Bas e *bases;

I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);

Is it possible without writing an adapter? Is there a better way? Is
there an existing adapter?
What's wrong with:

for (std::vector<Ba se *>::iterator i = bases.begin(); i !=
bases.end(); ++ i)
delete *i;

It's only two lines; and it's clear what is happening. I don't think
you'll be able to beat that. If it's something you do frequently you
could write a utility function like:

template <class Tvoid delete_all (T &cont) {
typedef typename T::iterator iter_t;
for (iter_t i(cont.begin()) ; i != cont.end(); ++ i)
delete *i;
cont.clear();
}
Example:

struct A { ... };

void f () {

vector<A *x;
list<A *y;
set<A *z;

x.push_back(new A);
x.push_back(new A);
y.push_back(new A);
y.push_back(new A);
z.insert(new A);
z.insert(new A);

delete_all(x);
delete_all(y);
delete_all(z);

}
Jason
Jun 27 '08 #3
Daniel Pitts <ne************ ******@virtuali nfinity.netwrit es:
I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);

Is it possible without writing an adapter? Is there a better way? Is
there an existing adapter?
Doesn't seem so... You'd better write your own my_delete:

template <class T>
struct my_delete : std::unary_func tion<T, void>
{
void operator()(T* t)
{
delete t;
}
};

This one:

std::for_each(b ases.begin(), bases.end(), std::ptr_fun(op erator delete));

compiles, but doesn't work(dtor is not called)...

--
William

http://williamxu.net9.org

Underdogging:
The tendency to almost invariably side with the underdog in a
given situation. The consumer expression of this trait is the
purchasing of less successful, "sad," or failing products: "I know
these Vienna franks are heart failure on a stick, but they were so sad
looking up against all the other yuppie food items that I just had to
buy them."
-- Douglas Coupland, "Generation X: Tales for an Accelerated
Culture"
Jun 27 '08 #4
Daniel Pitts <ne************ ******@virtuali nfinity.netwrot e:
I have std::vector<Bas e *bases;

I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);

Is it possible without writing an adapter? Is there a better way? Is
there an existing adapter?
From Stroustrup's book.

struct Delete_ptr {
template<class TT* operator()(T* p) const { delete p; return 0; }
};

....

transform(s.beg in(),s.end(),s. begin(),Delete_ ptr());
Jun 27 '08 #5
In article <48************ **********@news razor.net>,
ne************* *****@virtualin finity.net says...
I have std::vector<Bas e *bases;

I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);

Is it possible without writing an adapter? Is there a better way? Is
there an existing adapter?
Boost Pointer Container Library.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #6
On Jun 4, 5:43 am, "Daniel T." <danie...@earth link.netwrote:
Daniel Pitts <newsgroup.spam fil...@virtuali nfinity.netwrot e:
I have std::vector<Bas e *bases;
I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);
Is it possible without writing an adapter? Is there a better
way? Is there an existing adapter?
From Stroustrup's book.
struct Delete_ptr {
template<class TT* operator()(T* p) const { delete p; return 0; }
};
...
transform(s.beg in(),s.end(),s. begin(),Delete_ ptr());
[To the original poster: ignore this: it is from an
obsessional nitpicker, only for expert nitpickers.]

Note that formally, the above still has undefined behavior,
since it leaves a deleted pointer in the container for a (very)
short time. The correct way of doing this would be:

struct Deleter
{
template< typename T >
void operator()( T*& p ) const
{
T* tmp = NULL ;
std::swap( p, tmp ) ;
delete tmp ;
}
} ;

...

std::for_each( s.begin(), s.end(), Deleter() ) ;

(Note that it even uses swap. Can't get much more in than
that.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #7
On Jun 4, 7:25 am, James Kanze <james.ka...@gm ail.comwrote:
On Jun 4, 5:43 am, "Daniel T." <danie...@earth link.netwrote:
Daniel Pitts <newsgroup.spam fil...@virtuali nfinity.netwrot e:
I have std::vector<Bas e *bases;
I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);
Is it possible without writing an adapter? Is there a better
way? Is there an existing adapter?
From Stroustrup's book.
struct Delete_ptr {
template<class TT* operator()(T* p) const { delete p; return 0; }
};
...
transform(s.beg in(),s.end(),s. begin(),Delete_ ptr());

[To the original poster: ignore this: it is from an
obsessional nitpicker, only for expert nitpickers.]

Note that formally, the above still has undefined behavior,
since it leaves a deleted pointer in the container for a (very)
short time. The correct way of doing this would be:
What has undefined behavior? If you are talking about the transform
over all, or the () operator, neither are undefined. It is well-
defined that it leaves an invalid pointer in the container for a very
short time. What's undefined is if something attempts to dereference
that pointer during that time.
Jun 27 '08 #8
On Jun 4, 6:08 pm, "jason.cipri... @gmail.com"
<jason.cipri... @gmail.comwrote :
On Jun 4, 7:25 am, James Kanze <james.ka...@gm ail.comwrote:
On Jun 4, 5:43 am, "Daniel T." <danie...@earth link.netwrote:
Daniel Pitts <newsgroup.spam fil...@virtuali nfinity.netwrot e:
I have std::vector<Bas e *bases;
I'd like to do something like:
std::for_each(b ases.begin(), bases.end(), operator delete);
Is it possible without writing an adapter? Is there a better
way? Is there an existing adapter?
From Stroustrup's book.
struct Delete_ptr {
template<class TT* operator()(T* p) const { delete p; return 0; }
};
...
transform(s.beg in(),s.end(),s. begin(),Delete_ ptr());
[To the original poster: ignore this: it is from an
obsessional nitpicker, only for expert nitpickers.]
Note that formally, the above still has undefined behavior,
since it leaves a deleted pointer in the container for a (very)
short time. The correct way of doing this would be:
What has undefined behavior? If you are talking about the
transform over all, or the () operator, neither are undefined.
It is well- defined that it leaves an invalid pointer in the
container for a very short time. What's undefined is if
something attempts to dereference that pointer during that
time.
A pointer, after delete, may not even be read or copied (since
one of the effects of delete could be to render its value
"trapping") . Which means that it is not Copiable, and thus,
you've violated the requirements of the standard containers.

In practice, of course, there are very, very few implementations
where it might actually trap: to do so means 1) that the
hardware can trap on such pointers (Intels IA-32 is the only one
I know of where this might currently be a problem), 2) that the
library actually does free the memory in a way that unmaps it
(none that I know of do---they all keep the memory mapped to the
process for potential future use), 3) that the compiler actually
does the copy in such a way that might trap (I think some Intel
compilers do), and 4) that std::vector actually does try to copy
it. That last point is, of course, the ultimate guarantee;
std::vector will normally only copy anything if you try to
increase the size of the vector.

But the standard still says that all of the elements must be
copiable, even if there's no earthly reason for the vector to
copy.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #9
In article <da************ *************** *@earthlink.vsr v-
sjc.supernews.n et>, da******@earthl ink.net says...

[ ... ]
The implementation I presented doesn't read or copy any pointers after
the delete. The object is deleted, then the pointer is assigned NULL. If
the code I presented is "technicall y undefined" then so is:

delete p;
p = NULL;
Not so. An item in a container is required to be copyable. _We_ all know
that in a vector, for example, the contents are only ever copied in
reaction to things YOU do, such as a push_back when it's used up all the
memory already reserved. Nonetheless, the standard requires that all
items in a collection _always_ be copyable and assignable, even if you
_don't_ do anything that would force copying of the contents while it's
not copyable. Of course, the same goes for assignment.

In your snippet above, p is (apparently) not in a container, so the
container requirements don't apply.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #10

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

Similar topics

4
6573
by: bartek d | last post by:
Hello, I have a class which is used to encapsulate a RenderMan Interface variable. Generally speaking, such variable may be of integral, float, string type, or an array of those. I thought I could implement it by using a void pointer and a dynamically created std::vector. The vector could be accessed by typed accessor methods which would cast it to appropriate type, or throw an exception in
4
9799
by: Hitesh Bhatiya | last post by:
Hi all, I have written a small program to accept some socket connections, which are then added to a vector (using push_back). But after a few calls to the push_back function, it deleted the object that was added last. Could someone please tell me why this happens ? Am I doing something wrong here ?
3
3595
by: Markus Dehmann | last post by:
I have a two different value types with which I want to do similar things: store them in the same vector, stack, etc. Also, I want an << operator for each of them. class Value{}; // this would be "public interface Value{}" in Java! class IntValue : public Value{ private: int _value; public:
4
1704
by: Casper | last post by:
Is there features/containers of standard C++ or the STL which will assist in minimizing memmory fragmentation upon creation of a huge ammount of objects on the heap? Currently my application allocates 50.000 objects using "new". I can store the pointers to those objects in a container/collection class and indeed this assists in processing (sort, delete etc.) but is there any way for me to make my "new"'ed object resist in some previously...
24
2866
by: Rv5 | last post by:
Rookie c++ question, but Ive spent the last 5 years doing Java, where everytime I created an object I used new. In c++ I can create my objects without and its confusing me just a little. I have a class called polynomial. Its a nothing little class right now, with just int variables, a basic container class. Im using it as I go through some tutorials, but in this particular tutorial its telling me to do polynomial *first = new...
6
1997
by: R.Z. | last post by:
i'm using a class from some api that is said to automatically call its destructor when its out of scope and deallocate memory. i create instances of this class using "new" operator. do i have to explicitly call delete on these instances when i no longer need them?
6
3260
by: lokchan | last post by:
i want to create a vector of pointer s.t. it can handle new and delete but also have std::vector interface can i implement by partial specialization and inherence like follow ? #include <vector> #include <algorithm> template <typename T> struct delete_ptr {
7
3605
by: Ziyan | last post by:
I am writing a C/C++ program that runs in background (Linux). Therefore, normally no output would be written into standard output. However, sometimes I want to have debug message collected and sent tho network to a client so that errors and debug messages can be displayed simultaneously anywhere. I tried to use a std::stringstream to do the job. I created the stringstream in main() and pass it as pointer into a few threads. Those threads...
11
1769
by: letz | last post by:
Hi, We have a class whose objects are to be allocated in shared memory. To do that a ShmManager base class is defined so that operator new and delete are redefined to allocate segments in shared memory. A typical class "Foo" then inherit from ShmManager to have get this behaviour. class ShmManager {
0
8946
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
8774
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
9447
Oralloy
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...
0
8186
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
6735
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
6031
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();...
0
4550
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
3261
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
2180
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.