Re: Why doesn't the class/object keep its internal data properly when returned from function?
Rob <someidunknown1234@yahoo.com> writes:
I have a vector of a class type and when I create an object inside a
function and return that and add it to the vector, it doesn't properly
keep the data inside it. So I have a few questions:
1. Is this because it loses scope since it wasn't created with "new"?
2. If I do create it with new, but the vector holds objects not
pointers, will the vector's "delete" operator function still handle
deleting all those pointers?
CODE 1:
//Doing without "new"
SomeClass create(string name)
{
return SomeClass( name );
}
int main()
{
std::vector<SomeClass> p;
p.push_back( create( "Fred" ) );
}
CODE 2:
//Doing with "new"
SomeClass create(string name)
{
return *( new SomeClass( name ) );
}
int main()
{
//Will calling "delete p" also delete all the pointers created
for the data it holds?
std::vector<SomeClass> p;
p.push_back( create( "Fred" ) );
}
Both should work well. The second will leak memory (because you're
taking copies of the objects instead of keeping the pointers).
Things go better when you present fully compilable code:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class SomeClass {
public:
string name;
SomeClass(string aName):name(aName){};
};
void dump(vector<SomeClass>& v){
vector<SomeClass>::iterator it;
int i;
for(i=0,it=v.begin();it!=v.end();i++,it++){
cout<<i<<": "<<it->name<<endl;
}
}
SomeClass create1(string name)
{
return SomeClass( name );
}
void code1(void)
{
std::vector<SomeClass> p;
p.push_back( create1( "Fred" ) );
p.push_back( create1( "Merc" ) );
dump(p);
}
SomeClass create2(string name)
{
return *( new SomeClass( name ) );
}
void code2(void)
{
std::vector<SomeClass> p;
p.push_back( create2( "Fred" ) );
p.push_back( create2( "Merc" ) );
dump(p);
}
int main(void){
code1();
code2();
return(0);
}
/*
-*- mode: compilation; default-directory: "~/src/tests-c++/" -*-
Compilation started at Mon Apr 28 19:01:04
p=test-create ; cd /home/pjb/src/tests-c++/ ; g++ -o $p ${p}.c++ && ./$p
0: Fred
1: Merc
0: Fred
1: Merc
Compilation finished at Mon Apr 28 19:01:04
*/
--
__Pascal Bourguignon__