Search code examples
c++overloadingnew-operatortypename

Type name at the end of c++ expression;


I am learning c++ operator overloading, and I have met to this code

/*Global overloading*/
void* operator new(size_t size, char c) {
    cout<<"overloaded"<<endl;
    void * ptr;
    ptr = malloc(size);

    if(ptr != NULL) {
        *((char*) ptr) = c;
    }

    return ptr;
}

int main() {
    char * c = new('k') char;

    cout<<*c<<endl;
    return 0;
}

Specially, is strange for me the name char at the end of first line of function main. Please tell me what kind of expression is it, and how to understand?


Solution

  • new is an operator, that can optionally take arguments. Usually this argument will be a pointer to the memory where the object should be constructed (placement new), but in this case, you are defining a new operator that takes a char as an argument, and proceed to use it in main with 'k' as its argument. The entire expression new(...) serves as the operator in this context, and is followed by the type to construct as you are used to. It's really just a variation of new char to call the specified overload of operator new.

    Note that new(...) type does not just allocate the memory, it also calls the constructor of type, which you cannot modify by overloading. The operator new() functions are only used to provide the memory into which to construct the object. With type being char, that's not relevant, but with class types it is.

    The typical usage is to use an overload that accepts a pointer to some memory, and returns that pointer verbatim (placement new), allowing the calling code to supply its own memory like so:

    char* incompletelyConstructedArray = new char[allocSize];
    elementType* element = new(&incompletelyConstructedArray[elementLocation]) elementType;
    

    This constructs a single object of type elementType within the memory region allocated above. std::vector<> needs to do this under the hood to avoid default constructing objects when it grows its internal memory. But normal user code should be blissfully unaware that new() even exists...