CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Nov 2008
    Posts
    87

    placement new operator

    #include <iostream>
    using namespace std;

    class addition
    {
    int a, b;

    public:
    addition()
    {
    a=0;
    b=0;
    }

    addition(int x, int y)
    {
    a = x;
    b = y;
    }

    void show()
    {
    cout << a << " ";
    cout << b << "\n";
    }

    addition operator+(addition op2);
    };

    addition addition:perator+(addition op2)
    {
    addition temp;
    temp.a = op2.a + a;
    temp.b = op2.b + b;
    return temp;
    }

    int main()
    {
    char* buf=new char[100];
    addition* a1=new (buf) addition(1,3);//placement new operator
    return 0;
    }

    Queries:
    i. Is it possible to create object at a memory location on heap? i.e. let's say memory locaiton 2134433 present on heap....If yes, pl provide the code?

    ii. In the above code, what is the use of placement new opearator as we dont know address of memory location where object is getting creating?

  2. #2
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: placement new operator

    No, placement new operator used to construct a raw memory at a specific location.
    Thanks for your help.

  3. #3
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: placement new operator

    Just to sum up:

    Placement new allows the construction of an object at a specific memory location, that was previously allocated.

    So it is possible to construct things at specific locations, but it is impossible to request an allocation at a specific location.

    At best, you can give a hint to operator new (not the new operator), but this hint is typically ignored.

    Your code example looks really badly written. Typically, placement new is used for objects like vectors. It allows for the allocation of raw space, and then create objects into that raw space 1 by 1.

    In your example, raw memory is first allocated, at the address buf, then an addition object is created in the memory location pointed to by buf.

    The resulting a1 pointer points to the same place as buf , although it is of type addition* rather than char*. Note that buf != a1 given pointer offset and sizeof objects.

    Your example is bad because you allocate 100 bytes for an object who's size isn't 100 bytes (not wrong but inefficient). Clean-up will be especially ugly. This is a blatant example of trying to use a nifty functionality when a simple new would have done the trick.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  4. #4
    Join Date
    Jul 2002
    Posts
    2,543

    Re: placement new operator

    Placement new operator may be used for writing custom memory allocators. If you are interesting to place new objects in specific pre-allocated memory area, use placement new. Knowing absolute memory address is useless, I cannot think about situation, when it is necessary to place some C++ object at address 2134433 or something like this. Maybe this can be done for some kind of hacking?

  5. #5
    Join Date
    Nov 2008
    Posts
    87

    Re: placement new operator

    Can I request you to give 1 practical exaxple and its implementation?

  6. #6
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: placement new operator

    Quote Originally Posted by [email protected] View Post
    Can I request you to give 1 practical exaxple and its implementation?
    Code:
    #include <stdexcept>
    #include <cstddef>
    
    template <typename T>
    class StupidVector //implements a max size of 16 vector
    {
    public:
        StupidVector() : values(static_cast<T*>( ::operator new[](16 * sizeof(T)))),
                         size (0)
        {
        }
    
        void push_back(const T& input)
        {
            if (size = 15) throw std::out_of_range("out of range: 16");
    
            ++size;
            new (values+size) T(input); //copy construct the input at values+size
        }
    
        ~StupidVector()
        {
            for(size_t i = 0; i < size; ++i)
            {
                (values+i)->~T(); //destroy all the Ts that were built
            }
            ::operator delete[](values);
        }
    
    
    private :
        T* values;
        size_t size;
    };
    This is a basic idea: Allocate a lot of space at once, and then placement construct objects as you need them. In this example, I made a VERY simple vector implementation, that is immediately allocated to hold 16 objects, but won't grow.

    Note that this code was not tested, and may be dreadfully broken. The idea should be correct thought. I'd appreciate being told if if anything is wrong, or the way I do things are sub-optimal.

    Depending on your needs (IMO), it might be easier to just use std::allocator<T>::allocate() and std::allocator<T>:eallocate(). Since all containers use allocators anyways, and it is always an extra level of abstraction. That, and it avoids having to pass some sizeof objects.

    EDIT: This bears repeating though, unless you are a library writer, or writing very low level memory components, you should never have to do this. And if you think you do think it through twice. There is almost always a better solution.
    Last edited by monarch_dodra; July 5th, 2010 at 12:03 PM.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured