Unable to assign a class variable in overwriten operator new

Viewed 38

Visual Studio 2022, C++14

I'm trying to overload operator new to assign a value to a variable in the newly allocated memory. The variable value is being overwritten when the object is initialized. I can't figure out how to assign a value in operator new and have it persist during the object's initialization.

I think the sequence of operations is to create space using new and then to initialize the object, x. During the initialization process, x.link is being set to nullptr. I would like to keep the value that is set in new.

The code is:

#pragma once
class x {
    x* link;
public:
    x() { }
    void * operator new (size_t size);
}; // class x
#include "x.h"
#include <stdlib.h>
    
void* x::operator new(size_t size) {
    x* y = (x*)malloc(size);
    y->link = (x*)0xdeadbeef;
    return y;
}; // void * new (size_t size) 
    
class obj {
    void somefun() {
        x* y = new x();
    }
};
0 Answers
Related