Allocating memory

hey guys,I am reading an article which I will post below,

https://www.codeproject.com/Articles/4795/C-Standard-Allocator-An-Introduction-and-Implement

it is explaining how std::allocators work.


They go onto discuss how the new and delete keyword are actually implemented

1
2
3
4
5
6
 A* a = ::operator new(sizeof(A)); 
a->A::A();
if ( a != 0 ) {  // a check is necessary for delete
    a->~A();
    ::operator delete(a);
}


I understand the first line we are calling operator new to allocate memory with malloc as far as I know

but the next line is what I don't understand a->is calling A's constructor,I have never seen this syntax before and never knew it was possible to create an object like this?

thanks
It's pseudo syntax. For instance, you don't pass sizeof(A) to new in real C++.

Maybe it should have been written less like C++. In English:

1
2
3
4
5
6
7
8
operator new:
  Set an A pointer to newly allocated memory the size of A
  Call A's constructor on the pointer.
  Return the pointer.

operator delete:
  If the given pointer is null, do nothing.
  Otherwise, Call the destructor on the pointer. And free the allocated memory. 

Last edited on
Why can't you pass sizeof(A) to new in real C++?

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int main()
{

    // allocate memory with operator new
    void* mem = ::operator new(sizeof(int));
    // create object/type (int) in the memory we allocated
    int* integer = new(mem) int;
    *integer = 7;

    cout << *integer << endl;

}


the following code will compile and execute fine,we are allocating memory enough for the size of an int


but as you said

1
2
3
4
5
6
7

A* a = ::operator new(sizeof(A)); 
a->A::A();
if ( a != 0 ) {  // a check is necessary for delete
    a->~A();
    ::operator delete(a);
}


is not valid C++ code,I don't know why the author didn't say it was pseudo code,yeah very poor choice on his part,quite confusing

thanks
Last edited on
adam2016 wrote:
Why can't you pass sizeof(A) to new in real C++?

I didn't actually say you "can't", I said you "don't", but should have added "usually" in the sense that if you want an object you just use the type unless you're doing something "fancy".
Topic archived. No new replies allowed.