sizeof

 
void* buffer = operator new(100);


How do I verify the size of buffer after executing the above statement?
above statement does not compile.

in general you cannot "verify" the size of a buffer that is allocated via new or malloc. both new and malloc guarantee to allocate the amount of memory you specify/need or else they return NULL (or throw).

Thanks for suggestion.

1
2
3
4
5
6
7
#include <iostream>
using namespace std;
int main()
{
	void* buffer = operator new(100);
	return 0;
}


Above is the usage of operator new(), which compiles on VC++ 9.0
In that case I retract my first statement and stand correct.

However I still stand by my second statement.

Bizarre... I've never seen new used that way. I assume it is the
equivalent of new char[100].



Here is something I found that explains operator new nicely:
http://www.cprogramming.com/tutorial/operator_new.html

This is what I learned:
The relationship between Operator New and the New Keyword

Don't be confused by the fact that there is both a new keyword and an operator new. When you write:

MyClass *x = new MyClass;

there are actually two things that happen--memory allocation and object construction; the new keyword is responsible for both. One step in the process is to call operator new in order to allocate memory; the other step is to actually invoke the constructor. Operator new lets you change the memory allocation method, but does not have any responsibility for calling the constructor. That's the job of the new keyword.

As it turns out, it is actually possible to invoke the constructor without calling operator new. That's the job of placement new (covered below).

So, since he's allocating a void* buffer of 100 bytes, he only needs operator new -- instead of the new keyword (which would involve object construction of 100 bytes...)


I still have to read up on placement new -- but its intent is to control exactly what memory is allocated...
[edit] Rather -- it is used to avoid allocating memory: the object is constructed at a specific place in memory (a previously allocated block, shared memory, etc) [/edit]


Wow. Bizarre stuff...
Last edited on
@jsmith: I reviewed some of the uses of word "new" as follows:

- new operator: allocates memory by calling operator new and calls constructor

- operator new: You can use it to assign raw memory without calling the constructor. It is equivalent to malloc in C, which also doesn't call the constructor of the object

- placement new: It takes two parameters: 1) raw memory assigned by operator new and 2) Pointer that is to be initialized with the raw memory and it does exactly that. It is used when there is a raw memory, which has to be placed in a specific memory location. Really useful when designing a shared memory system.

There is a similar relation between delete operator and operator delete.
Last edited on
Topic archived. No new replies allowed.