Creating an object in allocated memory...

I don't know if that is possible.

Page 1 of 1

11 Replies - 1189 Views - Last Post: 17 June 2008 - 07:19 AM Rate Topic: -----

#1 Nextor  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-June 08

Creating an object in allocated memory...

Post icon  Posted 13 June 2008 - 02:44 AM

Hi all.
I hope some guru out there could help me to show me if that is possible.

There's two ways to create an object. One is calling the constructor explicitly in our code:

TClass object(arguments);



and the other is creating it dinamically with 'new':

TClass* pObject = new TClass(arguments);



Now, I'd like to know if it's possible to create an object in a space of memory whis has been already allocated. For example, we allocate an amount of memory which is enough to take an object:

void* pointer = malloc(sizeof(TClass));



and then, use that pointer to create an object in... It's that possible?

Thanx a lot

Is This A Good Question/Topic? 0
  • +

Replies To: Creating an object in allocated memory...

#2 perfectly.insane  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 70
  • View blog
  • Posts: 644
  • Joined: 22-March 08

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 03:15 AM

It's called placement new.

Example:

void* pointer = malloc(sizeof(TClass));
TClass* obj = new (pointer) TClass(arguments);


Was This Post Helpful? 1
  • +
  • -

#3 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 119
  • View blog
  • Posts: 1,565
  • Joined: 25-January 07

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 03:23 AM

New and malloc does almost the same thing with a small difference. malloc returns you just the memory chunk with void pointer to it so you need to typecast it while using again plus need to initialize it. [this is not recommended to be used in C++]

In case of new you tell it about what type of structure you need in memory and by giving constructor of object you can also initialize it.

If you want to do it using malloc only then you can allocate memory using malloc, typecast it for the object's class and use some function to initialize it . but that's not the proper way to do it and it is not guaranteed that it will always work [I mean behavior is undefined.].




--EDIT--

View Postperfectly.insane, on 13 Jun, 2008 - 03:45 PM, said:

It's called placement new.

Example:

void* pointer = malloc(sizeof(TClass));
TClass* obj = new (pointer) TClass(arguments);



wow! you are so fast!!!

--EDIT--

This post has been edited by AmitTheInfinity: 13 June 2008 - 03:24 AM

Was This Post Helpful? 0
  • +
  • -

#4 Nextor  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-June 08

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 04:40 AM

WOW! Thank you guys for those light-fast answers!! :^: :^: :^:

Amit, yes, I tried that kind of mend but, as you said, the results are unpredictable since we don't use any constructor to initialize the object.

Insane, i did't know about that type of new. THANKS FOR ILLUMINATING ME. My life's gonna change from now on.

Thanks a load

This post has been edited by Nextor: 13 June 2008 - 04:47 AM

Was This Post Helpful? 0
  • +
  • -

#5 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 05:21 AM

Just a curious question: Why do you need this ability?

Usually that form of the new operator is used when you are overloading the new operator to control object creation. I have seen this done in instances where one wants to keep a collection contiguous (like your own array class), or in some cases where your create your own memory management system (like with a language interpreter).

But I am curious to know what other uses are out there -- it is not used all that often, and recommended even less.
Was This Post Helpful? 0
  • +
  • -

#6 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 119
  • View blog
  • Posts: 1,565
  • Joined: 25-January 07

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 05:27 AM

View PostNickDMax, on 13 Jun, 2008 - 05:51 PM, said:

Just a curious question: Why do you need this ability?

Usually that form of the new operator is used when you are overloading the new operator to control object creation. I have seen this done in instances where one wants to keep a collection contiguous (like your own array class), or in some cases where your create your own memory management system (like with a language interpreter).

But I am curious to know what other uses are out there -- it is not used all that often, and recommended even less.



You are right Nick. These methods are too sensitive and powerful [with the power of destruction if not used properly]. And as some saint (was he uncle of some hero? :blink: ) said on some holy day "big powers come with big responsibilities" we are supposed to use these kind of functionalities very carefully and with full knowledge. That's why they are not recommended [so that only advance users will dare to touch them. :) ]
Was This Post Helpful? 0
  • +
  • -

#7 Trogdor  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 15
  • View blog
  • Posts: 627
  • Joined: 06-October 06

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 05:45 AM

It was spiderman :)
Was This Post Helpful? 0
  • +
  • -

#8 Nextor  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-June 08

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 08:30 AM

View PostNickDMax, on 13 Jun, 2008 - 05:21 AM, said:

Just a curious question: Why do you need this ability?

Usually that form of the new operator is used when you are overloading the new operator to control object creation. I have seen this done in instances where one wants to keep a collection contiguous (like your own array class), or in some cases where your create your own memory management system (like with a language interpreter).

But I am curious to know what other uses are out there -- it is not used all that often, and recommended even less.


Yeah, the reason of using that feature is the second one you suggested: managing memory.

I coded a linked list template whose nodes contain an user defined object. I make use of this template to create lists whose nodes are created and deleted very often throughout the execution of the program. Since using new and delete too often isn't very optimal, I included a kind of recycle bin for nodes being deleted which could be recycled afterwards. The problem is that the object contained in a node must be destroyed when dumped to the recycle bin and constructed when recovered from the bin, hence the need to use the 'placement new'.

This post has been edited by Nextor: 13 June 2008 - 08:31 AM

Was This Post Helpful? 0
  • +
  • -

#9 perfectly.insane  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 70
  • View blog
  • Posts: 644
  • Joined: 22-March 08

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 02:43 PM

"Placement new" is useful for using high-performance allocators, such as ones that dispense fixed-size pieces of memory. This allows one to bypass the costs involved with using the library's allocator, which is meant to work for all cases, but won't be as efficient as a specific case. With fixed chunks, one can allocate a large block of memory one time with the library allocator, and use a simpler management system to keep track of what memory is used as the chunks are a fixed size.

You might find this useful.

http://www.boost.org.../doc/index.html
Was This Post Helpful? 0
  • +
  • -

#10 perfectly.insane  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 70
  • View blog
  • Posts: 644
  • Joined: 22-March 08

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 02:56 PM

Here's a small demonstration of the performance difference:

#include <iostream>
#include <windows.h>
#include <boost/pool/pool.hpp>

const int N = 1000000;

int main()
{
    LARGE_INTEGER start, end, freq;
    int** test;

    QueryPerformanceCounter(&start);

    test = new int*[N];
    for(int x = 0; x < N; x++) test[x] = new int(0);
    for(int x = 0; x < N; x++) delete test[x];
    delete [] test;

    QueryPerformanceCounter(&end);
    QueryPerformanceFrequency(&freq);

    std::cout << "Performance for library new: " << (double)(end.QuadPart - start.QuadPart) / freq.QuadPart << " seconds " << std::endl;

    QueryPerformanceCounter(&start);
    boost::pool<> p(sizeof(int));
    boost::pool<> p2(sizeof(int*) * N);

    test = (int**)p2.malloc();
    for(int x = 0; x < N; x++) test[x] = (int*)p.malloc();

    // Destroy memory
    p.purge_memory();
    p2.purge_memory();

    QueryPerformanceCounter(&end);
    QueryPerformanceFrequency(&freq);

    std::cout << "Performance for boost::pool: " << (double)(end.QuadPart - start.QuadPart) / freq.QuadPart << " seconds " << std::endl;
    return 0;
}



Which prints for me:
Performance for library new: 0.695817 seconds
Performance for boost::pool: 0.0813109 seconds
Was This Post Helpful? 0
  • +
  • -

#11 perfectly.insane  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 70
  • View blog
  • Posts: 644
  • Joined: 22-March 08

Re: Creating an object in allocated memory...

Posted 13 June 2008 - 03:11 PM

View PostAmitTheInfinity, on 13 Jun, 2008 - 03:23 AM, said:

In case of new you tell it about what type of structure you need in memory and by giving constructor of object you can also initialize it.

If you want to do it using malloc only then you can allocate memory using malloc, typecast it for the object's class and use some function to initialize it . but that's not the proper way to do it and it is not guaranteed that it will always work [I mean behavior is undefined.].


Just to add:

The main way that one could hurt oneself doing this is if the class contains virtual functions. And it's likely that one won't notice the issue until one actually does something that makes the compiler emit a vtable call (as to what this is is probably compiler-dependent to a limited degree). The constructor has to initialize the vtable (the invisible structure in objects that C++ uses to implement polymorphism). Anything without virtual functions can probably be initialized in a safe way using a special member function and malloc though (as these are just over-glorified structs with associated functions).
Was This Post Helpful? 0
  • +
  • -

#12 Nextor  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-June 08

Re: Creating an object in allocated memory...

Posted 17 June 2008 - 07:19 AM

WOW Insane, thanx a lot for your replies. I haven't had the time to check that yet but I'll do.

Thanx again man
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1