473,799 Members | 2,950 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 1214
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
3267
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
25215
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
2291
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
1887
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
4930
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
2809
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
2781
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
3466
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
2997
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
9686
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
9540
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
10475
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
10250
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
10222
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
9068
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
7564
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
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2938
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.