473,856 Members | 1,650 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why doesn't the class/object keep its internal data properly whenreturned from function?

Rob
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<Som eClassp;
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<Som eClassp;
p.push_back( create( "Fred" ) );
}
Jun 27 '08 #1
8 1218
Rob wrote:
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.
What do you mean?
So I have a few questions:

1. Is this because it loses scope since it wasn't created with "new"?
No.
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?
No.
>
CODE 1:

//Doing without "new"

SomeClass create(string name)
{
return SomeClass( name );
}

int main()
{
std::vector<Som eClassp;
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?
No.
std::vector<Som eClassp;
p.push_back( create( "Fred" ) );
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #2
On 2008-04-28 17:48, Rob wrote:
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"?
No, it is probably because you have not implemented the copy-constructor
correctly, but without seeing the code it is impossible to tell.
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?
No, and especially not if you return a copy of the new object and then
looses all references to it (like you do below).
CODE 1:

//Doing without "new"

SomeClass create(string name)
{
return SomeClass( name );
}

int main()
{
std::vector<Som eClassp;
p.push_back( create( "Fred" ) );
}
CODE 2:

//Doing with "new"

SomeClass create(string name)
{
return *( new SomeClass( name ) );
}
This creates a copy of the "newed" object which is then returned, the
"newed" object is then lost (since you have no pointers to it) which
means you are leaking memory.

--
Erik Wikström
Jun 27 '08 #3
Rob <so************ ***@yahoo.comwr ites:
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<Som eClassp;
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<Som eClassp;
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(strin g aName):name(aNa me){};
};

void dump(vector<Som eClass>& v){
vector<SomeClas s>::iterator it;
int i;
for(i=0,it=v.be gin();it!=v.end ();i++,it++){
cout<<i<<": "<<it->name<<endl;
}
}
SomeClass create1(string name)
{
return SomeClass( name );
}

void code1(void)
{
std::vector<Som eClassp;
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<Som eClassp;
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__
Jun 27 '08 #4
Rob
Things go better when you present fully compilable code:

Yes, sorry about that. My problem was that I was deleting stuff in the
destructor and I didn't realize that in calling the copy constructor,
it also calls the destructor too. So, do I have to create a separate
method (like "void destroy()" ) to release all memory instead of using
the destructor and then call it explicitly if I'm using the copy
constructor?
Jun 27 '08 #5
Rob wrote:
>Things go better when you present fully compilable code:

Yes, sorry about that. My problem was that I was deleting stuff in
the destructor and I didn't realize that in calling the copy
constructor, it also calls the destructor too. So, do I have to
create a separate method (like "void destroy()" ) to release all
memory instead of using the destructor and then call it explicitly
if I'm using the copy constructor?
No, but you probably have to have the copy constructor actually copy
everything, including things pointed to.
Bo Persson
Jun 27 '08 #6
Rob wrote:
>Things go better when you present fully compilable code:

Yes, sorry about that. My problem was that I was deleting stuff in the
destructor and I didn't realize that in calling the copy constructor,
it also calls the destructor too. So, do I have to create a separate
method (like "void destroy()" ) to release all memory instead of using
the destructor and then call it explicitly if I'm using the copy
constructor?
Not necessarily. You need a proper copy constructor. The copy constructor
should *copy* everything in the class. So that your copy has it's own copy
and it won't be effected by the destructor of the old object.

Since I really don't know what SomeClass is allocating I'll just throw up
some example of untested code.

class SomeClass
{
public:
SomeClass() { Foo = new int[100]; }
~SomeClass() { delete[] Foo; }
private:
int* Foo;
};

Now, that class is not complete. It needs to follow the rule of three. It
will need a copy constructor and an operator=. Otherwise when a copy is
made the old copy will delete Foo and effect both copies. So I need to do
something like: (Note: this code probably has a lot of bugs, just showing
concept).

class SomeClass
{
public:
SomeClass() { Foo = new int[100]; }
~SomeClass() { delete[] Foo; }
SomeClass( const SomeClass& rhs )
{
Foo = new int[100];
std::copy( rhs.Foo, Foo + 100, Foo );
}
SomeClass& operator=( SomeClass const& rhs )
{
delete[] Foo;
Foo = new int[100];
std::copy( rhs.Foo, Foo + 100, Foo );
return this;
}
private:
int* Foo;
};

The whole idea being that each instance of Foo keeps it's own resources.
Also note that if Foo was a std::vector<int none of this would be necessary
as std::vector already has the copy constructor and operator= overloaded and
would be called in the default constructor and operator=.

Since you didn't post SomeClass I really don't know what you're doing in
there, what your allocating or how you're allocating it.
--
Jim Langston
ta*******@rocke tmail.com
Jun 27 '08 #7
On Apr 28, 8:35 pm, Rob <someidunknown1 ...@yahoo.comwr ote:
Things go better when you present fully compilable code:
Yes, sorry about that. My problem was that I was deleting stuff in the
destructor and I didn't realize that in calling the copy constructor,
it also calls the destructor too.
It doesn't. But you're copying something; what is the lifetime
of the object you are copying?
So, do I have to create a separate method (like "void
destroy()" ) to release all memory instead of using the
destructor and then call it explicitly if I'm using the copy
constructor?
No. You have to define a copy constructor (and probably an
assignment operator) which works correctly.

What you really have to do, however, is acquire a copy of Scott
Meyers' "Effective C++" and read it.

--
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 #8
"Jim Langston" <ta*******@rock etmail.comwrite s:
[...]
SomeClass( const SomeClass& rhs )
{
Foo = new int[100];
std::copy( rhs.Foo, Foo + 100, Foo );
you mean:
std::copy( rhs.Foo, rhs.Foo + 100, Foo );
}
SomeClass& operator=( SomeClass const& rhs )
{
delete[] Foo;
Foo = new int[100];
std::copy( rhs.Foo, Foo + 100, Foo );
you mean:
std::copy( rhs.Foo, rhs.Foo+100, Foo );

or perhaps:

std::copy( rhs.Foo, rhs.Foo+sizeof( Foo)/sizeof(Foo[0]), Foo );
[...]
--
__Pascal Bourguignon__
Jun 27 '08 #9

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

Similar topics

1
3272
by: Sean W. Quinn | last post by:
Hey folks, I have a question regarding file handling, and the preservation of class structure. I have a class (and I will post snippets of code later in the post) with both primitive data structures (ints), and more complex data structures (strings and vectors) in it, and would like to write the entire class to a data file that could then be read back and loaded. However I'm having difficulty with this -- I found out (due to an...
149
25298
by: Christopher Benson-Manica | last post by:
(Followups set to comp.std.c. Apologies if the crosspost is unwelcome.) strchr() is to strrchr() as strstr() is to strrstr(), but strrstr() isn't part of the standard. Why not? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
1
2296
by: Tom | last post by:
I've googled, and read, and stripped out code, and rewritten code, and still can't get a System.Threading.Timer to work. (I hereby publicly admit that I'm a failure here...) Could someone please take a quick look at this and tell me where I'm going wrong? My actual use is more complex, but when I couldn't get that to work I created a new service project and figured to get a simple threading timer going first then I'd revamp my actual code...
4
1890
by: Luke Matuszewski | last post by:
Here are some questions that i am interested about and wanted to here an explanation/discussion: 1. (general) Is the objectness in JavaScript was supported from the very first version of it (in browsers) ? What about the new syntax of creating a object using { 'propName1':'propValue1', 'propName2':'propValue2', 'propName3':{ /* another object */ } } - from what version of JScript/JavaScript it was supported (from what browsers versions) ?...
16
4935
by: Dany | last post by:
Our web service was working fine until we installed .net Framework 1.1 service pack 1. Uninstalling SP1 is not an option because our largest customer says service packs marked as "critical" by Microsoft must be installed on their servers. Now german Umlaute (ä, ü, ö) and quotes are returned incorrectly in SOAP fault responses. This can be easily verified: Implement the following in a web service method (just raises a SOAPException with a...
2
2812
by: timpera2501 | last post by:
I am a newb to OOP programming and I'm only just starting with C#. I've done a TON of reading lately, and I'm currently in the process of modifying some of the function provided by the "TimeTracker Start-up Kit" for my needs. ****** BEGINING OF TIME TRACKER SUMMARY ***** First, in the "TimeTracker Start-Up Kit" they appear to have tried to set it up so that it can be expanded to any number of different datasource types (SQL, Access,...
9
2797
by: Neo Geshel | last post by:
I have strip-mined, strip-searched, and completely exhausted the Internet (up to the 30th page on Google, with 100 results per page!!), all without finding an answer to my question AS TO WHY IT IS IMPOSSIBLE TO PROGRAMMATICALLY ADD A BUTTON TO A DYNAMICALLY CREATED PAGE. Or, to be more precise, why it is impossible to have an onClick sub respond to that button’s Click event. My main page has only one line:
7
3467
by: mathieu | last post by:
Hello, I did read the FAQ on template(*), since I could not find an answer to my current issue I am posting here. I have tried to summarize my issue in the following code (**). Basically I am trying to hide the `complexity` of template from the user interface. If you look at the code DataSet should be the object that my user manipulate. Unfortunately by doing so the object returned by DataSet::Get is a FloatingPt, so without the virtual...
4
2999
by: James Kanze | last post by:
On Aug 13, 5:32 am, Jack Klein <jackkl...@spamcop.netwrote: While you've made a number of important points: In other words, according to the C standard, any signal
0
10697
jinu1996
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...
1
10786
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10389
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...
1
7932
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
7097
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
5762
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
4578
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
4175
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3202
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.