473,324 Members | 2,179 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

operator new question

hello,

When we use new operator to user defined type, constructor will be called
and a memory block is created in heap. My question: where those non-pointer
data members belonging to this user-defined class will be create? on heap or
on stack? Obviousely it's on heap.

OK, if it's on heap, how stack unwinding meachnism can destroy those data
members when exception happened? Since it's not on stack, it's on heap!

I read the c++ progamming language by BStroustrup and can not find the
answer, please help understanding. Thanks very much!

John
Jul 22 '05 #1
8 1232

"john sun" <jo*****@sbcglobal.net> skrev i en meddelelse
news:E7*****************@newssvr16.news.prodigy.co m...
hello,

When we use new operator to user defined type, constructor will be called
and a memory block is created in heap. My question: where those non-pointer data members belonging to this user-defined class will be create? on heap or on stack? Obviousely it's on heap.

OK, if it's on heap, how stack unwinding meachnism can destroy those data
members when exception happened? Since it's not on stack, it's on heap!

I read the c++ progamming language by BStroustrup and can not find the
answer, please help understanding. Thanks very much!

John

Well..... all members of the object will be stored in the heap, regardless
of whether they are pointers or not. Also, a pointer has no destructor so
nothing happens if it leaves scope:

class C {...};
void test()
{
C c_stack;
C* c_ptr = new C();
if (...)
throw 0;
}

When test returns (or throws), the destructor of c_stack will be called.
c_ptr is not an object (it is a plain pointer) so there will be a memory
leak and a live object somewhere, possible holding on to other ressources.

In short, only use pointer variables when you want to create an object with
a scope reaching outside the point, where it is created. Also in those cases
you should wrap the pointer in a smart-pointer class such as the ones you
can find at boost.

Kind regards
Peter Koch Larsen
Jul 22 '05 #2

"john sun" <jo*****@sbcglobal.net> wrote in message news:E7*****************@newssvr16.news.prodigy.co m...
hello,

When we use new operator to user defined type, constructor will be called
and a memory block is created in heap. My question: where those non-pointer
data members belonging to this user-defined class will be create? on heap or
on stack? Obviousely it's on heap.


The non-static members (pointer or otherwise) will be created with the object
(i.e., on the heap). Don't confuse a pointer with the object it points to. If
there is a member that is a pointer, then the object it points to is whatever the
class sets it to.

Jul 22 '05 #3
john sun wrote:
hello,

When we use new operator to user defined type, constructor will be
called and a memory block is created in heap.
Yes, though the C++ standard doesn't actually call it heap.
My question: where those
non-pointer data members belonging to this user-defined class will be
create? on heap or on stack? Obviousely it's on heap.
Yes.
OK, if it's on heap, how stack unwinding meachnism can destroy those
data members when exception happened? Since it's not on stack, it's on
heap!


Stack unwinding doesn't have anything to do with dynamically allocated
objects. It rather destroys the local variables of a function when an
exception occurs during that function.

Jul 22 '05 #4

"john sun" <jo*****@sbcglobal.net> wrote in message
news:E7*****************@newssvr16.news.prodigy.co m...
hello,

When we use new operator to user defined type, constructor will be called
and a memory block is created in heap. My question: where those non-pointer data members belonging to this user-defined class will be create? on heap or on stack? Obviousely it's on heap.

OK, if it's on heap, how stack unwinding meachnism can destroy those data
members when exception happened? Since it's not on stack, it's on heap!

Put something on the stack that will delete it for you.

Have a look at std::auto_ptr.

void f()
{
auto_ptr<T> p = new T;
if( error )
throw "error";
}

However the function exits the T will be deleted.
I read the c++ progamming language by BStroustrup and can not find the
answer, please help understanding. Thanks very much!

John

Jul 22 '05 #5
here is example:
#include "stdafx.h"
#include <stdio.h>
#include <memory>
using namespace std;

class O
{
public:
O(){};
~O(){};
}
;
class A1
{
O* o;
public :
A1()
{
o=new O();
printf("in A1 ctor\n");
}
~A1()
{
delete o;
printf("in A1 dtor\n");
};
};

class A
{
public :
A(){printf("in A ctor\n");};
~A(){printf("in A dtor\n");};
};
class B
{

auto_ptr<A> a;
A1 a1;
public:
B():a(new A)
{
throw 1;
}
~B(){printf("in B dtor\n");}
};
int main(int argc, char* argv[])
{
try{
B *b=new B();
}
catch(int)
{
printf("catch block\n");
}
return 0;
}
After running a1 and a destructor will be called. This confused me. Since b
is created in heap, and a and a1 is also on heap, how come exception can
call a1 and a's destructor.

Thanks for furthermore clarifying.

Best regards to all!
Jul 22 '05 #6
Fortunately
After running a1 and a destructor will be called. This confused me. Since b
is created in heap, and a and a1 is also on heap, how come exception can
call a1 and a's destructor.

First, there is the concept of a "fully constructed object". An object is
fully constructed when its constructor body has been run. When an exception
happens during object creation, all the things that are fully constructed get
their destructors run.

In this case what happens when you call new B:

1. sizeof(B) bytes is allocated by the global operator new.
2. B's subobjects are constructed. B::a is constructed by dynamically
creating an A object (I'll omit the details of this) dynamically and feeding
it to the auto_ptr constructor. B::a is now fully constructed at this point.
3. B::a1 is default constructed. B::a1 is now fully constructed.
4. The constructor body of B is run.
5. The throw expression is encountered.
6. The compiler now destructs all of the fully constructed parts of B in reverse order:
B::a1 is destroyed.
7. B::a is destroyed, the auto_ptr destructor deletes the referenced A object.
8. The global operator delete is called to return the memory used by B.
9. The stack is unwound up to the point where the handler is found... and control
is transferred there.

Jul 22 '05 #7
Thanks Ron!

I know those steps, I am confused the fully constructed object could be
destructed. Since those fully constructed object is on the heap in my
example. If you say fully constructed object can be destructed there should
be some limitations. Because the following code also demo the fully
constructed object will not be destroyed.

class A{};

void foo()
{
A * a=new A();
throw 1;
return 0;
}

int main{
try {
foo();
}
catch(...)
{};
return 0;
}

Object pointed by a will not be deleted even it's a fully constructed
object. I know because c++ lost track of a pointed object. But why in our
previous example, the sub object which is also created on heap will be
deleted if exception throw? Looks like to me c++ can track the subobject
what even it's created on heap or stack. What's the mechanism here?

Thanks very much for sharing and insightful discussion

John
"Ron Natalie" <ro*@sensor.com> wrote in message
news:40***********************@news.newshosting.co m...
Fortunately
After running a1 and a destructor will be called. This confused me. Since b is created in heap, and a and a1 is also on heap, how come exception can
call a1 and a's destructor.
First, there is the concept of a "fully constructed object". An object

is fully constructed when its constructor body has been run. When an exception happens during object creation, all the things that are fully constructed get their destructors run.

In this case what happens when you call new B:

1. sizeof(B) bytes is allocated by the global operator new.
2. B's subobjects are constructed. B::a is constructed by dynamically
creating an A object (I'll omit the details of this) dynamically and feeding it to the auto_ptr constructor. B::a is now fully constructed at this point. 3. B::a1 is default constructed. B::a1 is now fully constructed.
4. The constructor body of B is run.
5. The throw expression is encountered.
6. The compiler now destructs all of the fully constructed parts of B in reverse order: B::a1 is destroyed.
7. B::a is destroyed, the auto_ptr destructor deletes the referenced A object. 8. The global operator delete is called to return the memory used by B.
9. The stack is unwound up to the point where the handler is found... and control is transferred there.

Jul 22 '05 #8

"john sun" <jo*****@sbcglobal.net> wrote in message
news:t1*******************@newssvr31.news.prodigy. com...
Thanks Ron!

I know those steps, I am confused the fully constructed object could be
destructed. Since those fully constructed object is on the heap in my
example. If you say fully constructed object can be destructed there should be some limitations. Because the following code also demo the fully
constructed object will not be destroyed.

class A{};

void foo()
{
A * a=new A();
replace with "std::auto_ptr<A> a = new A; " and it will be destructed.
- A* is a pointer which has no destructor.
- std::auto_ptr<A> is an object with a defined destructor that, when called,
calls delete on the pointer it holds
throw 1;
return 0;
}

int main{
try {
foo();
}
catch(...)
{};
return 0;
}

Jul 22 '05 #9

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

Similar topics

7
by: Paul Davis | last post by:
I'd like to overload 'comma' to define a concatenation operator for integer-like classes. I've got some first ideas, but I'd appreciate a sanity check. The concatenation operator needs to so...
30
by: | last post by:
I have not posted to comp.lang.c++ (or comp.lang.c++.moderated) before. In general when I have a C++ question I look for answers in "The C++ Programming Language, Third Edition" by Stroustrup....
2
by: victor75040 | last post by:
Before you all start flaming me, I am not a student and this is not for any homework. Just someone learing c++ on their own. I am now up to the chapter in my book that describes operator...
2
by: wongjoekmeu | last post by:
Hello All, I have a question about a C++ listing that I don't understand from a book that I use to learn C++. In the listing a class String is declared and defined. The beginning look like this...
4
by: Mark Stijnman | last post by:
A while ago I posted a question about how to get operator behave differently for reading and writing. I basically wanted to make a vector that can be queried about whether it is modified recently...
20
by: Patrick Guio | last post by:
Dear all, I have some problem with insertion operator together with namespace. I have a header file foo.h containing declaration of classes, typedefs and insertion operators for the typedefs in...
2
by: Harry | last post by:
Hi all, I am writing a logger program which can take any datatype. namespace recordLog { enum Debug_Level {low, midium, high}; class L { std::ofstream os; Debug_Level cdl; const...
67
by: carlos | last post by:
Curious: Why wasnt a primitive exponentiation operator not added to C99? And, are there requests to do so in the next std revision? Justification for doing so: C and C++ are increasingly used...
56
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
18
by: Ranganath | last post by:
Why is throw keyword considered as an operator?
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.