473,498 Members | 359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about STL for dynamically allocating memory...

86 New Member
i have class Sum_class defines as...
Expand|Select|Wrap|Line Numbers
  1. class Sum_class
  2. {
  3. private:
  4.      int data_member1;
  5.      char* data_member2;
  6. public:
  7.      Sum_class()
  8.      { data_member2 = new char;
  9.      }
  10.      ~Sum_class()
  11.      { cout<<"Destructor called";
  12.          delete data_member2;
  13.          data_member2=0;
  14.      }
  15.      void get_input(void)
  16.      {
  17.      code.....
  18.      }        
  19.      void show_output(void)
  20.      { 
  21.      code....
  22.      }
  23. };
  24.  
  25. int main()
  26. {
  27.      vector<Sum_class> object;
  28.      char CONTINUE ='y';
  29.     while(CONTINUE!='n' || CONTINUE!='N')
  30. {
  31.          object.push_back(Sum_class()); // this will invoke constructor
  32.          ....
  33.          code...
  34. }
  35. ....
  36. code...
  37.  
  38. return EXIT_SUCCESS;
  39. }
  40.  
the problem is that the destructor will be invoked soon after the constructor is called as the objects scope are localised within the loop...

is there any way out so that i can declare objects dynamically using vector (as many as want)...and prevent the call of destructor.....
Apr 19 '07 #1
6 1291
gpraghuram
1,275 Recognized Expert Top Contributor
Hi,
If u make a change in the code then the destructor wont be called.
Check this code
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     vector<Sum_class*> object;
  4.     char CONTINUE ='y';
  5.     Sum_class *obj=NULL;
  6.     while(CONTINUE!='n' || CONTINUE!='N')
  7.     {
  8.         obj=new Sum_class();
  9.         //object.push_back(Sum_class()); // this will invoke constructor
  10.         object.push_back(obj);    }
  11.     return 0;
  12. }
  13.  
Thanks
Raghuram
Apr 19 '07 #2
ayan4u
86 New Member
ohhhhhhhh...how could i forget pointers...thnx...thnx..thnx...a lot....i forgot tht we can as well use pointers with STL.....thnx again
Apr 19 '07 #3
ayan4u
86 New Member
i thnk i was overwhelmed and thanked u too much(which i shldnt as i walked through ur suggestions).....u r idea dd solved the problem apparently(that it didnot call the destructor of the vector objects but for the temporary object obj) it itself came up with too many bugs.....for instance i am dynamically assigning memory for one of data members....so when i am invoking object.push_back(obj) i am actually invokin the default copy constructor.....i thnk the solution lies in an explict copy construtor.....

with your method i am gettn a warning:HEAP while debuggn.....


so i thnk custom made copy constructor is the answer.....wat say...
Apr 19 '07 #4
weaknessforcats
9,208 Recognized Expert Moderator Expert
Your problem is not an explicit copy consturctor.

Instead it is no copy constructor at all.

When you have no copy constructor, the compiler trots out its default constructor. This default copy constructor just does memberwise copy if your class data memebers. Specifically, it copies data_member2. Afterwards, the original object points to the same char as the copy. Whichever object calls its destructor, the data_member2 is deleted. Then when the other object calls its destructor you crash trying to delete data that already has been deleted.

Generally, classes wwith pointers as member require a copy constructor:

Expand|Select|Wrap|Line Numbers
  1. Sum_class::Sum_class(const Sum_class& orig)
  2. {
  3. this->data_member2 = new char;
  4. *this->data_member2 = *orig.data_member2;
  5. }
  6.  
Now the copy object has a copy of the original object's data_member2 and each object can now call its destructor without messing things up.

As a further note:

The worst thing you can do in a C++ program is pass pointers around. You cannot safely delete them unless you know there are no orther copies of the pointer in the program. I suggest you learn to use an Envelope class, sometimes canned a handle. The handle class can keep track ofd the number of instances of the pointer that still exist. Check Design Patterns. Look up the Bridge Pattern.
Apr 19 '07 #5
gpraghuram
1,275 Recognized Expert Top Contributor
Hi Ayan,
I gave u the solution with whatever info u have asked for and i was not expecting a thanks from u for the same.
Explain the problem clearly so that people can give u right solutions and get thanks from you.
Thanks
Raghuram
Apr 20 '07 #6
ayan4u
86 New Member
neways the problem is now solved....all i had to do is make few changes arnd....nonetheless ur suggestions are valuable....
Apr 20 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

14
3515
by: Peter Olcott | last post by:
I want to be able to efficiently build data structures at run-time. These data structures need to be accessed with minimal time. The only a few ways that come immediately to mind would be some...
10
1498
by: zhou xiang | last post by:
/////////////// code 1 start /////////////////////// char *GetString(void) { char p = "hello world"; return p; } void Test4(void) { char *str = NULL; str = GetString();
4
1270
by: Tony Johansson | last post by:
Hello Experts!! I have an easy question when you allocate memory by using new you allocate memory dynamically but what is it called when you allocate memory without using new. Here is an...
13
1646
by: Franklin Li | last post by:
Hi All, I find one example codes as below: int send() { char msg; ... delete msg; ..
7
3093
by: Fabian Wauthier | last post by:
Hi list, I am trying to dynamically grow a 2 dimensional array (Atom ***Screen) of pointers to a struct Atom (i.e. the head of a linked list). I am not sure if this is the right way to do it: ...
94
4635
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring...
6
2609
by: bwaichu | last post by:
Is my understanding of the allocation of these correct? I used fixed sized allocations for the example below, so I realize there is some optimization that can be done to those. I would like to...
12
2133
by: filia&sofia | last post by:
For example I would like to dynamically allocate memory for linked list (or complex struct etc.) that has not maximum number of elements. All that I can remember is that I have to have allocated...
6
1802
by: remlostime | last post by:
now, i write some code code1: int a; int main(){} code2: vector<inta(10000000); int main(){} after using g++ compile, and run it, code1 is broken, but code2 runs
19
3359
by: =?ISO-8859-1?Q?Nordl=F6w?= | last post by:
I am currently designing a synchronized queue used to communicate between threads. Is the code given below a good solution? Am I using mutex lock/unlock more than needed? Are there any resources...
0
7124
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,...
0
6998
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...
0
7200
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...
0
7375
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...
0
5460
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,...
1
4904
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...
0
4586
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...
0
3090
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...
0
1416
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 ...

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.