472,972 Members | 2,025 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

How to call a constructor explicitly if we want to allocate memory using malloc ?

I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc". This
will return me the required memory but the object is not initialized
properly as constructor same is not get called ( as per the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?

Oct 18 '06 #1
13 9503
shsingh wrote:
I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc". This
will return me the required memory but the object is not initialized
properly as constructor same is not get called ( as per the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?
Your create object on the heap with new, not malloc.

A *pA = new A;

You free the memory and object with delete.

delete pA;
Oct 18 '06 #2
shsingh wrote:
I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc".
This will return me the required memory but the object is not
initialized properly as constructor same is not get called ( as per
the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?
Use "placement new" (look it up).

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

shsingh wrote:
I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc". This
will return me the required memory but the object is not initialized
properly as constructor same is not get called ( as per the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?
You can use placement new.

buffer = malloc(/*...*/);
object = new (buffer) MyClass(/*...*/);

But later you have to call the destructor explicitly too:

object->~MyClass();
free(buffer);

Regards,
Bart.

Oct 18 '06 #4
shsingh wrote:
I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc". This
will return me the required memory but the object is not initialized
properly as constructor same is not get called ( as per the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?
You can't call a constructor. You can construct an object in
memory you provide (from malloc or anyplace else) with
placement new:

#include <new>

void* memory = malloc(sizeof T);
T* tp = new (memory) T;

Oct 18 '06 #5

Bart wrote:
shsingh wrote:
I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc". This
will return me the required memory but the object is not initialized
properly as constructor same is not get called ( as per the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?

You can use placement new.

buffer = malloc(/*...*/);
object = new (buffer) MyClass(/*...*/);

But later you have to call the destructor explicitly too:

object->~MyClass();
free(buffer);

Regards,
Bart.
Is that correct to construct the object on the memory allocated by
malloc? Is that behavior defined in standard C++? I think that the
memory should be allocated by operator new if you want to use placement
new.

Best Regards,
Robin.

Oct 18 '06 #6
zouyongbin wrote:
Bart wrote:
shsingh wrote:
I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc". This
will return me the required memory but the object is not initialized
properly as constructor same is not get called ( as per the behavior).
>
How to call a constructor explicitly if we want to allocate memory
using malloc ?
You can use placement new.

buffer = malloc(/*...*/);
object = new (buffer) MyClass(/*...*/);

But later you have to call the destructor explicitly too:

object->~MyClass();
free(buffer);

Regards,
Bart.

Is that correct to construct the object on the memory allocated by
malloc? Is that behavior defined in standard C++? I think that the
memory should be allocated by operator new if you want to use placement
new.
No. Placement new was invented specifically so you can use your own
memory allocator.

The memory doesn't even have to be "allocated" at all. If you were to
write an OS kernel in C++ you could just construct some object at
whatever physical address you like without ever allocating any memory.

Regards,
Bart.

Oct 18 '06 #7
Ron Natalie wrote:
shsingh wrote:
>I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc". This
will return me the required memory but the object is not initialized
properly as constructor same is not get called ( as per the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?
You can't call a constructor.
Can you call function? or is all that *you* can do writing an expression in
your code and then, if required, the implementation will call a function in
the course of the evaluation of that expression? As far as I know, the
standard does not set linguistic precedence for the using the active voice
(we call a function/constructor) as opposed to the passive voice (a
function/constructor is called) in either case. So do you take a
linguistice license in the case of functions but not in the case of
constructors? If so, why?

You can construct an object in
memory you provide (from malloc or anyplace else) with
placement new:

#include <new>

void* memory = malloc(sizeof T);
T* tp = new (memory) T;

Best

Kai-Uwe Bux

Oct 18 '06 #8
Kai-Uwe Bux wrote:
Ron Natalie wrote:
>shsingh wrote:
>>I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc".
This will return me the required memory but the object is not
initialized properly as constructor same is not get called ( as
per
the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?
You can't call a constructor.

Can you call function? or is all that *you* can do writing an
expression in your code and then, if required, the implementation
will call a function in the course of the evaluation of that
expression? As far as I know, the standard does not set linguistic
precedence for the using the active voice (we call a
function/constructor) as opposed to the passive voice (a
function/constructor is called) in either case. So do you take a
linguistice license in the case of functions but not in the case of
constructors? If so, why?
You can call a function.

You cannot call a constructor directly, because it doesn't have a
name. Most attempts to "call a constructor" will create a temporary of
the class type instead.

class C {};

C::C(); // creates a temporary of class C
In practice, you invoke the constructor as part of executing a new
expression, like placement new.

Bo Persson
Oct 18 '06 #9
Bo Persson wrote:
Kai-Uwe Bux wrote:
>Ron Natalie wrote:
>>shsingh wrote:
I have a class A containing some map as data variables. I creat an
object of class A on heap by allocatiing memory by using "malloc".
This will return me the required memory but the object is not
initialized properly as constructor same is not get called ( as
per
the behavior).

How to call a constructor explicitly if we want to allocate memory
using malloc ?

You can't call a constructor.

Can you call function? or is all that *you* can do writing an
expression in your code and then, if required, the implementation
will call a function in the course of the evaluation of that
expression? As far as I know, the standard does not set linguistic
precedence for the using the active voice (we call a
function/constructor) as opposed to the passive voice (a
function/constructor is called) in either case. So do you take a
linguistice license in the case of functions but not in the case of
constructors? If so, why?

You can call a function.

You cannot call a constructor directly, because it doesn't have a
name. Most attempts to "call a constructor" will create a temporary of
the class type instead.

class C {};

C::C(); // creates a temporary of class C

Come on, can't you spot a troll?

If you create a temporary, doesn't it in fact mean you managed to call
a constructor? Kai-Uwe is just f****ng with you. Now, you've joined
the debacle by introducing your "directly" into the argument. So what
does "you cannot call a constructor directly" actually mean? Does it
mean you *can* call it, or that you *cannot* call it? Drop the
"directly" and explain. Can you? You can't. Directly, I mean. :-)
(now that's what I call a word play)
In practice, you invoke the constructor as part of executing a new
expression, like placement new.
"Invoke", "call"... Isn't it all the same thing? At some point in
the past I grew tired of this debate and now try not to beat this
half-dead horse. Refraining from torturing the poor animal is highly
recommended to all readers.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 18 '06 #10
Bo Persson wrote:
You cannot call a constructor directly, because it doesn't have a
name.
I have read this argument several times. However, I do not understand the
inference: I agree that constructors do not have names. But where in the
standard do you find the other hypothesis needed for the inference, namely
that you need a name to call someting? This additional assumption might be
something that you consider natural because functions are called by using
their names. However, constructor calls do not need to be parallel to
function calls. In my view, it is perfectly natural to regard placement new
as a special syntax provided by the standard for calling constructors.
This syntax does not require constructors to have names, since the class
name is used instead. The compiler then deduces for you which constructors
is to be used (somewhat like it deduces which function you meant to call in
the case of overloaded functions). So again: where in the standard do you
find the provision that something needs to have a name for us to be able to
call it?

Most attempts to "call a constructor" will create a temporary of
the class type instead.

class C {};

C::C(); // creates a temporary of class C
And how does that not call a constructor? If I am not mistaken, an
expression of the form classname( arguments ) is even named an "explicit
constructor call" in the standard.

In practice, you invoke the constructor as part of executing a new
expression, like placement new.
So I can invoke the constructor but I cannot call it? Where in the standard
would I find the distinction between "to invoke" and "to call". As far as I
can see, the two words are both used synonymously in the standard with
regard to constructor calls.
Best

Kai-Uwe Bux
Oct 20 '06 #11
How to call a constructor explicitly if we want to allocate
memory using malloc ?
This thread has been an excellent read for me. "placement new" is a
concept I had not heard of before. Since I do some kernel level
development it is an excellent language feature because you often are
given context buffer space that you overlay a structure onto. Without
placement new, there ar two suboptimal solutions: either avoid
constructors or put a pointer to the object (instead of the object
itself) in the context buffer and new/delete it.

If there are any other concepts that might especially be useful in
kernel level development, please mention.

Oct 21 '06 #12
* Kai-Uwe Bux:
[about "can't call constructor" urban myth]

I recently ran into yet another formulation in the standard that uses
the "call" terminology, namely 1.9/15, about an initializer like

Foo object( arg1, arg2, arg3 ... );

"the resulting construct is a function call upon a constructor function,
with expression-list as an argument list; such a function call is a
full-expression".

Can't be very much more clear than that, I think. ;-)

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 21 '06 #13
44****@email.com wrote:
How to call a constructor explicitly if we want to allocate
memory using malloc ?

This thread has been an excellent read for me. "placement new" is a
concept I had not heard of before. Since I do some kernel level
development it is an excellent language feature because you often are
given context buffer space that you overlay a structure onto. Without
placement new, there ar two suboptimal solutions: either avoid
constructors or put a pointer to the object (instead of the object
itself) in the context buffer and new/delete it.
There are many non-portable ways that you could manage objects at a
fixed memory location in a kernel (finding the address of the
constructor, relocating the stack, telling the linker where to
construct the objects) but there are at least a few ways that you could
do it using standard C++ features:

- placement new
- overloaded new operator
- pointers to fixed addresses (works for POD only)
If there are any other concepts that might especially be useful in
kernel level development, please mention.
As mentionned above, you can overload new and delete. You can also
provide your own allocator to the standard containers. Such things
might be useful in a kernel implementation. However, some features such
as exceptions and RTTI may be unavailable or may need special
implementation.

The following link may be interesting:
http://netlab.ru.is/exception/LinuxCXX.shtml

Regards,
Bart.

Oct 21 '06 #14

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

Similar topics

9
by: Dario | last post by:
This is a technical C++ post regarding the Microsoft runtime error R6025 Pure Virtual Function Call that sometime occurs in programs compiled with Microsoft Visual C++ 6.0. Please consider the...
2
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray =...
24
by: Jazper | last post by:
hi i have this problem. i made a class deverted by CRootItem with implementation of IDisposable-Interface. i made a test-funktion to test my Dispose-Method.... but when set a breakpoint in my...
10
by: Shea Martin | last post by:
If I have a class Foo like this: class Foo { public: Foo() { mData = new char; } ~Foo()
5
by: Frederick Gotham | last post by:
If we have a simple class such as follows: #include <string> struct MyStruct { std::string member; MyStruct(unsigned const i) {
7
by: michael | last post by:
Hi All, I have written the following to illustrate a problem. I know I have some magic numbers etc please ignore them. What I do not follow is why the line marked results in a call to the...
20
by: royashish | last post by:
Hi all , A question to the C++ fraternity , Why the Copy constructor ? Was suggested in Effective C++ , In Case the Object contains a Char* , a assignment operator = makes the two object...
12
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? ...
15
by: asm23 | last post by:
Hi, everyone, I'm studying the <<Thinking in C++>volume Two. In Chapter One, the example code : Auto_ptr.cpp //------------------------------------------------------- #include <memory> #include...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
3
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.