473,569 Members | 2,617 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on auto_ptr, Which function will call first?

Hi, everyone, I'm studying the <<Thinking in C++>volume Two. In
Chapter One, the example code : Auto_ptr.cpp
//-------------------------------------------------------
#include <memory>
#include <iostream>
#include <cstddef>
using namespace std;

class TraceHeap {
int i;
public:
static void* operator new(size_t siz) { //*****NOTE A
void* p = ::operator new(siz);
cout << "Allocating TraceHeap object on the heap "
<< "at address " << p << endl;
return p;
}
static void operator delete(void* p) {
cout << "Deleting TraceHeap object at address "
<< p << endl;
::operator delete(p);
}
TraceHeap(int i) //*******NOTE B
: i(i)
{
;
}
int getVal() const { return i; }
};

int main() {
auto_ptr<TraceH eappMyObject(ne w TraceHeap(5));
cout << pMyObject->getVal() << endl; // Prints 5
}
//------------------------------------------------------------------

My question is :

In My code: which code will be called first? The *NOTE A* or *NOTE B* ?
And Why?

I'm debugging through this code and found that *NOTE A* will called
first. Can someone explained it?
When I trace into the *new* function, the *siz* value is 4. I don't know
why it will be 4?

Thank you for reading my message.
Oct 3 '08 #1
15 1859
asm23 wrote:
Hi, everyone, I'm studying the <<Thinking in C++>volume Two. In
Chapter One, the example code : Auto_ptr.cpp
//-------------------------------------------------------
#include <memory>
#include <iostream>
#include <cstddef>
using namespace std;

class TraceHeap {
int i;
public:
static void* operator new(size_t siz) { //*****NOTE A
void* p = ::operator new(siz);
cout << "Allocating TraceHeap object on the heap "
<< "at address " << p << endl;
return p;
}
static void operator delete(void* p) {
cout << "Deleting TraceHeap object at address "
<< p << endl;
::operator delete(p);
}
TraceHeap(int i) //*******NOTE B
: i(i)
{
;
}
int getVal() const { return i; }
};

int main() {
auto_ptr<TraceH eappMyObject(ne w TraceHeap(5));
cout << pMyObject->getVal() << endl; // Prints 5
}
//------------------------------------------------------------------

My question is :

In My code: which code will be called first? The *NOTE A* or *NOTE B* ?
And Why?
The 'operator new' function is the class-wide allocation function.
Before any object of that class can be constructed in free store, the
memory has to be allocated. That's why the allocation happens before
the construction.
I'm debugging through this code and found that *NOTE A* will called
first. Can someone explained it?
I think I just did.
When I trace into the *new* function, the *siz* value is 4. I don't know
why it will be 4?
The object of type TraceHeap that you're creating has a single data
member, 'int i', and no virtual functions or base classes. It's
reasonable to conclude that nothing contributes to the size of the
object except the data members. On your platform 'int' probably has the
size of 4 bytes... Try printing out 'sizeof(TraceHe ap)' somewhere, what
do you get.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 3 '08 #2
Victor Bazarov wrote:
>
The 'operator new' function is the class-wide allocation function.
Before any object of that class can be constructed in free store, the
memory has to be allocated. That's why the allocation happens before
the construction.
Thanks Victor. I understand, I confused with *allocation* and
*construction*. But now, I know they are different and executing
sequence of them.
>
I think I just did.
The object of type TraceHeap that you're creating has a single data
member, 'int i', and no virtual functions or base classes. It's
reasonable to conclude that nothing contributes to the size of the
object except the data members. On your platform 'int' probably has the
size of 4 bytes... Try printing out 'sizeof(TraceHe ap)' somewhere, what
do you get.

V
oh, Yes, the sizeof(TraceHea p) is 4. But I still have a puzzle. Why
these is a *static* before the overloaded new and delete operation?
I do know static function doesn't pass the *this* parameters. But in
this case, a static new or a normal new seems have no difference.

Thank you for help me.

Oct 4 '08 #3
On Oct 3, 6:00 pm, asm23 <asmwarr...@gma il.comwrote:
Hi, everyone, I'm studying the <<Thinking in C++>volume Two.
In Chapter One, the example code : Auto_ptr.cpp
//-------------------------------------------------------
#include <memory>
#include <iostream>
#include <cstddef>
using namespace std;
class TraceHeap {
int i;
public:
static void* operator new(size_t siz) { //*****NOTE A
void* p = ::operator new(siz);
cout << "Allocating TraceHeap object on the heap "
<< "at address " << p << endl;
return p;
}
static void operator delete(void* p) {
cout << "Deleting TraceHeap object at address "
<< p << endl;
::operator delete(p);
}
TraceHeap(int i) //*******NOTE B
: i(i)
{
;
}
int getVal() const { return i; }
};
int main() {
auto_ptr<TraceH eappMyObject(ne w TraceHeap(5));
cout << pMyObject->getVal() << endl; // Prints 5
}
//------------------------------------------------------------------
My question is :
In My code: which code will be called first? The *NOTE A* or
*NOTE B* ? And Why?
NOTE A, obviously. The trivial reason is because that is what
the language requires. Of course, the reason the language
requires this is that it couldn't possibly work otherwise: you
have to allocate the memory for the object before you can
construct it.
I'm debugging through this code and found that *NOTE A* will called
first. Can someone explained it?
Think. What would it mean if NOTE B were called before NOTE A.
When I trace into the *new* function, the *siz* value is 4. I don't know
why it will be 4?
Because that's the size of a TraceHeap object on your machine.

--
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
Oct 4 '08 #4
On Oct 3, 6:17 pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
The 'operator new' function is the class-wide allocation
function. Before any object of that class can be constructed
in free store, the memory has to be allocated. That's why the
allocation happens before the construction.
Just a nit, but that last sentence applies to all objects, not
just those dynamically allocated. One of the particularities of
C++ is that there is NO syntax for calling a constructor without
formally allocating memory. (In the case of placement new, of
course, the "allocation " is purely formal. But you still have
to tell the compiler what memory it should use.)

--
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
Oct 4 '08 #5
asm23 wrote:
>
oh, Yes, the sizeof(TraceHea p) is 4. But I still have a puzzle. Why
these is a *static* before the overloaded new and delete operation?
I do know static function doesn't pass the *this* parameters. But in
this case, a static new or a normal new seems have no difference.

Thank you for help me.
You are right, it doesn't matter. The operators new and delete are
static, whether you write 'static' or not.

The author of this code perhaps believed that it is more clear if this
is stated explicitly. Maybe it is not? :-)
Bo Persson
Oct 4 '08 #6
Bo Persson wrote:
asm23 wrote:
>oh, Yes, the sizeof(TraceHea p) is 4. But I still have a puzzle. Why
these is a *static* before the overloaded new and delete operation?
I do know static function doesn't pass the *this* parameters. But in
this case, a static new or a normal new seems have no difference.

Thank you for help me.

You are right, it doesn't matter. The operators new and delete are
static, whether you write 'static' or not.

The author of this code perhaps believed that it is more clear if this
is stated explicitly. Maybe it is not? :-)
Bo Persson

Thanks Bo, I see.
Oct 4 '08 #7
James Kanze wrote:
NOTE A, obviously. The trivial reason is because that is what
the language requires. Of course, the reason the language
requires this is that it couldn't possibly work otherwise: you
have to allocate the memory for the object before you can
construct it.
>I'm debugging through this code and found that *NOTE A* will called
first. Can someone explained it?

Think. What would it mean if NOTE B were called before NOTE A.
>When I trace into the *new* function, the *siz* value is 4. I don't know
why it will be 4?

Because that's the size of a TraceHeap object on your machine.

--
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
Thanks, James.
Now, I understand the important concept of " allocating before
construction ".

I think the author overload the operator new of TraceHeap is just to
show some message.

static void* operator new(size_t siz) { //*****NOTE A
void* p = ::operator new(siz);
cout << "Allocating TraceHeap object on the heap "
<< "at address " << p << endl;
return p;
}

the parameter *size_t siz* will be filled at compiling time. So, the
compiler will set the siz value to sizeof(TraceHea p).

Is my understanding right? Thanks.
Oct 4 '08 #8
James Kanze wrote:
On Oct 3, 6:17 pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
>The 'operator new' function is the class-wide allocation
function. Before any object of that class can be constructed
in free store, the memory has to be allocated. That's why the
allocation happens before the construction.

Just a nit, but that last sentence applies to all objects, not
just those dynamically allocated. One of the particularities of
C++ is that there is NO syntax for calling a constructor without
formally allocating memory. [...]
I don't doubt that you're right, but I'd like to know
what this
std::string("hu h?")
is if it's not the explicit invocation of a constructor.

Schobi
Oct 5 '08 #9
Hendrik Schober wrote:
James Kanze wrote:
>On Oct 3, 6:17 pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
>>The 'operator new' function is the class-wide allocation
function. Before any object of that class can be constructed
in free store, the memory has to be allocated. That's why the
allocation happens before the construction.

Just a nit, but that last sentence applies to all objects, not
just those dynamically allocated. One of the particularities of
C++ is that there is NO syntax for calling a constructor without
formally allocating memory. [...]

I don't doubt that you're right, but I'd like to know
what this
std::string("hu h?")
is if it's not the explicit invocation of a constructor.
It is a creation of a temporary object, which of course *causes* a call
to the constructor (and later a destructor at the end of the object's
lifetime, which is impossible for you to prevent, BTW).

You *may* call it an "explicit invocation", and start beating that dead
horse again, but let me just make a note here: if it's an invocation,
it's not explicit. The constructor is *invoked* or *called* by the
execution environment when you *create an object*. The language of the
Standard is such that there cannot be *direct* call to the constructor
simply because constructors do not have names and cannot be found during
lookup.

No, back to the subject at hand. James said you cannot call (or invoke,
if you will) a constructor without allocating memory first, and not that
you can't call a constructor (or cause its invocation). When you do

std::string("bl eh")

the system will *still* allocate memory for you first, and then invoke
the constructor to construct the object in that memory. You do not call
the constructor. You do not allocate memory. The syntax is for object
creation, and you give the system the responsibility for the low-level
stuff.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 5 '08 #10

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

Similar topics

4
9431
by: alg | last post by:
I am learning to use "auto_ptr" and found that the following 2 line would not compile: auto_ptr<Cat> pCat; pCat = new Cat(6); until I changed it to the one: auto_ptr<Cat> pCat(new Cat(6));
45
3008
by: Jamie Burns | last post by:
Hello, I realise that I just dont get this, but I cannot see the need for auto_ptr. As far as I have read, it means that if you create an object using an auto_ptr, instead of a raw pointer, then the object will get cleaned up when the method/function ends. Isn't this what happens if you just declare an object without using a pointer at all?...
4
2042
by: ma740988 | last post by:
// file sltest.h #ifndef SLTEST_H #define SLTEST_H class CallbackBase // herb shutters gotW source .. { public: virtual void operator()() const { }; virtual ~CallbackBase() = 0; };
10
2527
by: ma740988 | last post by:
Part of my confusion here is certainly my ignorance of templates and std::auto_ptr. Two topics, I've perused but need to really _delve_ into. In any event, consider the 'test' source. # include <iostream> # include <memory> class CallbackBase { public: virtual void operator()() const { };
10
317
by: Lloyd Dupont | last post by:
how do I redefine the new operator? for all the structure I use at once! (some of them comes from C include files). The rationale: I'm writting a managed C++ wrapper around C API (external headers & structure definition). it's very handy to use "new SCRIPT_ITEM;" however I want to handle OutOfMemory gracefully, that is dealloc everything...
2
1762
by: flopbucket | last post by:
I saw the following post a few messages back and am trying to understand exactly why this is so. Thanks for the information. My comments begin with **. The original post was arguing that STL code that tried to have a container of auto_ptr (which I know is wrong, but thats not the point here) should *NOT* compile according to the standard....
5
1683
by: Raider | last post by:
Is it exception-safe to write like this: void foo(auto_ptr<Tx) { ... } void bar() { foo(auto_ptr<T>(new T(...));
9
2914
by: dragoncoder | last post by:
Hi all, I am trying to understand the auto_ptr_ref role in the implementation of auto_ptr<>. I read the information on net but still not 100% sure of it. My plan is as follows. 1. To see the behaviour of std::auto_ptr. 2. To implement a pkt::auto_ptr without auto_ptr_ref. 3. Check out the limitations of pkt::auto_ptr as compared to...
2
2370
by: timlyee | last post by:
int *p = new int; auto_ptr<intap1 = p; //will fail on 3 1 auto_ptr<intap1(p); //ok 2 *ap1 = 12; // 3 the first situation has called : explicit auto_ptr(_Ty *_Ptr = 0) _THROW0() the second : auto_ptr(auto_ptr_ref<_Ty_Right) _THROW0()
0
7924
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. ...
0
8130
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...
0
7979
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...
0
6284
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...
1
5514
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...
0
5219
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...
0
3653
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...
1
2115
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
0
940
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...

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.