What happen between operator new and constructor function?

I wanna know the new and construct order when new a class, so I write the fuction as bellow:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <string>
#include <iostream>
#include <vector>

using namespace std;

typedef enum COLOR
{
    RED,
    WHITE,
    BLUE,
    YELLOW
}COLOR_ENUM;

class Flower
{
public:
    void *operator new(size_t size);
    Flower();
    Flower(COLOR_ENUM FlowerColor);
private:
    COLOR_ENUM m_Color;
};

Flower::Flower():m_Color(RED)
{
    return;
}

Flower::Flower(COLOR_ENUM FlowerColor) 
{
    m_Color = FlowerColor;
    return;
}

void *Flower::operator new(size_t size)
{
    cout<<"New function"<<endl;
    
    return ::operator new(size); //correct function,first call new, then call construct function
    
    //Flower f;
    //return &f; //still call new and construct funciton, but I think it should be crash when calling construct function
    
    //return NULL; //just call new
}

int main( void )
{
    Flower *p, *q;
    p = new Flower;
    q = new Flower(WHITE);
    return 0;
}


So I want to know what hanppen between new and construct function.

Thx.
I'm not certain I understand your question. The (normal) new operator calls the constructor with the parameters you give it.
Hi Zhuge:
There is 2 questions:

1. When function
void *Flower::operator new(size_t size)
return a pointer which is "dirty", why constructor function can be called and the program not crash?
1
2
3
4
5
6
7
void *Flower::operator new(size_t size)
{
    cout<<"New function"<<endl;
    
    Flower f;
    return &f; //still call new and construct funciton, but I think it should be crash when calling construct function    
}


2. When function
void *Flower::operator new(size_t size)
return a NULL pointer, why the constructor function isn't called?
1
2
3
4
5
6
void *Flower::operator new(size_t size)
{
    cout<<"New function"<<endl;
    
    return NULL; //just call new
}


thanks
Last edited on
1. You are returning the address of unallocated stack space. The C++ standard does not mandate that a program crash if it accesses unallocated memory. It says the behavior is undefined. In your case, the memory happens
to remain mapped in your process' address space so the construction does not crash, but all the same it writes to memory that is not allocated.

2. The compiler knows better than to call the constructor with a NULL address. C++ allows memory allocation to fail by returning NULL, and it elides the constructor call at that point (as otherwise the behavior is undefined, but on most platforms address 0 is write-protected or unmapped so will result in a program crash) and allows the user to
recover from the failure programmatically.
Ok, thank u jsmith
Topic archived. No new replies allowed.