473,796 Members | 2,875 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vector.swap and heap / stack

Hi,
suppose I have a vector allocated on the heap. Can I use a temporary
(stack based vector) and swap to clear it, or is this unsafe. e.g.

vector<int> *v;
vector<int> tmp;
v->swap(tmp); // is this an unsafe transfer between heap and stack
// or does the allocator handle it safely?
regards,
steve
Jul 19 '05 #1
5 10030
"Steve Hill" <st**********@m otorola.com> wrote in message
news:c2******** *************** ***@posting.goo gle.com...
| suppose I have a vector allocated on the heap. Can I use a temporary
| (stack based vector) and swap to clear it, or is this unsafe. e.g.
|
| vector<int> *v;
| vector<int> tmp;
| v->swap(tmp); // is this an unsafe transfer between heap and stack
| // or does the allocator handle it safely?

It is safe.
You could write:
void clearV(vector<i nt>& c)
{ vector<int>().s wap(c); }

And call it with various instances:

auto_ptr<vector <int> > p = new vector<int>(4,5 );
clearV( *p );

vector<int> l(4,5);
clearV( l );

static vector<int> s(4,5);
clearV( s );

All is safe and sound...

hth
--
http://www.post1.com/~ivec
Jul 19 '05 #2
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:WI******** *********@newsr ead3.news.pas.e arthlink.net...
Yes, this is safe. But note that you needn't define
'tmp', you could use a temporary expression:

v->swap(std::vect or<int>());
This line is actually illegal in standard C++, unlike:
std::vector<int >().swap(*v); // this is ok

A temporary can only be bound to a *const* reference,
while the parameter of swap is a non-const reference.
(MSVC typically supports the line you posted as an
extension of the language, but it is non-standard).
BTW, why not just use the 'clear()' member function:

v->clear();


Because clear does not free the memory allocated by *v,
while using the swap trick typically will (although
the standard does not formally guarantee this).
Regards,
Ivan
--
http://www.post1.com/~ivec
Jul 19 '05 #3
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:Y2******** ********@newsre ad3.news.pas.ea rthlink.net...
v->swap(std::vect or<int>());


This line is actually illegal in standard C++, unlike:
std::vector<int >().swap(*v); // this is ok


Actually, I didn't mean either one.

I meant:

std::swap(*v, std::vector<int >());


Note that this illegal, for the same reason as the
first example ( v->swap(std::vect or<int>()) ).
std::vector<int >() is a temporary, and both of the swap
calls you suggested expect a non-const reference as a
first parameter.
This is unlike the valid option:
std::vector<int >().swap(*v); // this is ok
Here swap is invoked as a member function of the
temporary, which is legal ISO C++.
BTW, why not just use the 'clear()' member function:

v->clear();


Because clear does not free the memory allocated by *v,


AFAIK, it *will* free the memory occupied by
its elements (assuming of course that if the
elements are UDT's which manage memory, they do so
correctly).


The standard mandates that v.clear() is equivalent to
calling v.erase( v.begin(), v.end() ) -- in 23.1.1.
The erase function does not cause the vector's memory
to be reallocated (or freed). Its effect is to (23.2.4.3)
invalidate "all the iterators and references *after* the
point of the erase". Which means that the iterator
returned by v.begin() shall not be invalidated by the
call to v.clear().
Basically, clear() will set the *size* of a vector to 0,
but will leave the *capacity* of the vector unchanged.
The memory block that std::vector has allocated to
store its contents will not be freed.
while using the swap trick typically will (although
the standard does not formally guarantee this).


Can you elaborate, please?


v1.swap(v2) will exchange the memory blocks that are
associated with the two vectors. This is typically done
by swapping the pointers stored within each vector.

When using: std::vector<int >().swap(*v);
std::vector<int >() typically does not allocate any
memory (its capacity is zero). After the memory blocks
are exchanged, v will receive the block of capacity 0,
and the temporary owns the memory previously associated
with v -- which will be released by the temporary's
destructor.

Well, I hope this is not too confused... it's getting
late here.

Sincerely,
Ivan
--
http://www.post1.com/~ivec
Jul 19 '05 #4
"tom_usenet " <to********@hot mail.com> wrote in message
news:3f******** ******@news.eas ynet.co.uk...
| On Thu, 21 Aug 2003 01:37:01 +0200, "Ivan Vecerina"
| <ivecATmyrealbo xDOTcom> wrote:
|
| >The standard mandates that v.clear() is equivalent to
| >calling v.erase( v.begin(), v.end() ) -- in 23.1.1.
| >The erase function does not cause the vector's memory
| >to be reallocated (or freed). Its effect is to (23.2.4.3)
| >invalidate "all the iterators and references *after* the
| >point of the erase". Which means that the iterator
| >returned by v.begin() shall not be invalidated by the
| >call to v.clear().
|
| It certainly shall! erase invalidates iterators to erased elements, as
| well as iterators to elements after the erase.

From my reading of the standard (see the *after* above),
I believe that the following is legal code:

void deleteOddValues (std::vector<in t>& v)
{
std::vector<int >::iterator scan = v.begin();
while( scan != v.end() )
if( *s % 2 ) v.erase(scan);
else ++scan;
}

The iterator from which the erasing starts remains valid
(although it must not be dereferenced if it now equals end()).

By extension, the following should also be ok:
std::vector<int >::iterator b = v.begin();
v.clear();
assert( b == v.end() && b == v.begin() );

Therefore, v.clear() cannot free the memory occupied by
the vector (the allocator's interface doesn't support
in-place shrinking of allocated memory).
And the std::vector<int >().swap(v) trick has its place...
Kind regards,
Ivan
--
http://www.post1.com/~ivec


Jul 19 '05 #5
On Fri, 22 Aug 2003 17:53:44 +0200, "Ivan Vecerina"
<iv**@myrealbox .com> wrote:
| It certainly shall! erase invalidates iterators to erased elements, as
| well as iterators to elements after the erase.

From my reading of the standard (see the *after* above),
I believe that the following is legal code:

void deleteOddValues (std::vector<in t>& v)
{
std::vector<int >::iterator scan = v.begin();
while( scan != v.end() )
if( *s % 2 ) v.erase(scan);
else ++scan;
}

The iterator from which the erasing starts remains valid
(although it must not be dereferenced if it now equals end()).

By extension, the following should also be ok:
std::vector<int >::iterator b = v.begin();
v.clear();
assert( b == v.end() && b == v.begin() );

Therefore, v.clear() cannot free the memory occupied by
the vector (the allocator's interface doesn't support
in-place shrinking of allocated memory).
And the std::vector<int >().swap(v) trick has its place...


Apologies, you're correct according to the standard, if not according
to my expectations (although they have now been updated).

Tom
Jul 19 '05 #6

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

Similar topics

6
2675
by: Sayan | last post by:
How do I distinguish between a heap pointer and a stack pointer? I want the following to work: template<class T> bool isHeapPtr(T* p1,T* p2);//the function I want to write //... int a = 5; int *pas = &a; int *pah = new int; *pah = 10;
10
2296
by: gogogo_1001 | last post by:
Dear all, I don't understand why "delete" works well on destructing a object, but fails to destruct a vector of it. Any of your comment is highly appreciated! Following is the program that represent this problem:
3
3155
by: balu | last post by:
Hi Gurus I need a help. Im developing a C++ libaray. I don't whether user creates object in stack/heap. Is there a way to find object location? Balu.N
10
1943
by: Amit | last post by:
char *str1="amit"; char str2="mehta" strcat(str1,str2); It will crash, I feel str1 will be stored in code section. Once memory is allocated, you cannot change or append into this. Please correct me If I am wrong..
2
2857
by: Nick McCamy | last post by:
I have a question related to allocating on the stack. In this program below, are my following assumptions true? - variable a is allocated on the heap since it's static - variable b is allocated on the stack since it's a value type variable - variable d is allocated on the stack since it's a value type variable Where does variable "c" get allocated? It's a value type, but not foundwithin a method.
4
3355
by: Robbie | last post by:
Someone at work asked me this question: Value types--do they hit the heap or the pile? Well, I was a bit dumbfounded, because I never heard of the term "pile". I've heard of heap and stack, but what is a pile? Is it just another name for stack? Doing some reading, I found that value types use stack memory since the size can be determined at compile time and there's less overhead with this type of memory. So, I'm thinking this is...
6
7896
gpraghuram
by: gpraghuram | last post by:
HI All, Someone asked me the following question and i am not able to get an answer for this. In c++ how will you restrict 1)object creation in heap 2)object creation in stack Can anyoine throw some light into this Raghuram
0
2163
by: seper254 | last post by:
Hey I am in the middle of Java and I am having trouble drawing heap stack diagrams from code. I have two that I really need help with. First code: public class HEAPSTACK extends ConsoleProgram{ public void run(){ Integer n1=1; Integer n2=20; int computation=meth(n1,n2); println("computation:"+computation);
0
10003
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
9050
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
7546
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
6785
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
5441
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
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
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
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
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.