Re: Cleanup Technique
<brad.power@gmail.com> wrote in message...
Dont I need to call new to put the strings on the heap? If I just
declare 2 strings on the stack, won't they die when they go out of
scope?
Not if you 'store' them. They will be destroyed at end-of-scope, but, live
on in the 'container' (std::vector below).
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm> // copy
void VecRefFill( std::vector<std::string> &thevec ){
std::string S1( "Hello" );
std::string S2( "World" );
thevec.push_back( S1 );
thevec.push_back( S2 );
thevec.push_back( "Third string direct." );
return;
} // VecRefFill(vector<string>& )
// at this point, 'S1' and 'S2' are gone, but,
// they were copied into the vector.
std::vector<std::string> VecCopyFill(){
std::vector<std::string> thevec;
std::string S1( "Hello2" );
std::string S2( "World2" );
thevec.push_back( S1 );
thevec.push_back( S2 );
thevec.push_back( "Third string direct2." );
return thevec; // return a 'copy'
}
int main(){
std::vector<std::string> Vec1;
VecRefFill( Vec1 );
std::copy( Vec1.begin(), Vec1.end(),
std::ostream_iterator<std::string>( std::cout, "\n" ) );
std::cout<<std::endl;
std::vector<std::string> Vec2;
Vec2 = VecCopyFill();
std::copy( Vec2.begin(), Vec2.end(),
std::ostream_iterator<std::string>( std::cout, "\n" ) );
std::string GetItBack( Vec1.at(2) );
// std::cout<<GetItBack<<std::endl;
return 0;
} // main()
// at this point, 'Vec1' and 'Vec2' (and all their strings) are gone.
// all the dynamic memory stuff was handled for you.
/* -output-
Hello
World
Third string direct.
Hello2
World2
Third string direct2.
*/
Did that help any?
--
Bob R
POVrookie
- -
Get "Thinking in C++", 2nd ed. Volume 1&2 by Bruce Eckel
(available for free here. You can buy it in hardcopy too.):
http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html
Alf P. Steinbach's "Pointers" document:
http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf
The Dinkumware site has some very good documentation, try:
http://www.dinkumware.com/manuals/.
FAQ http://www.parashift.com/c++-faq-lite