简体   繁体   中英

What arguments does new take?

Does new in C++ call a constructor behind the scenes? Or is it the other way around?

I have seen code like new MyClass(*this) which confuses me, since I didn't know that new could take arguments.

Maybe that's because new can call a constructor and, as a result, it can take the arguments declared by a constructor?

MyClass(*this) creates an object of type MyClass by calling its constructor and passing *this as an argument. Putting new behind it means the object is allocated on the heap instead of the stack. It's not new which is taking the argument, it's MyClass .

There is a difference between new and operator new . The new operator uses a hidden operator new function to allocate memory and then it also "value-initializes" the object by calling its constructor with the parameters after the class name.

In your case you call new which allocates memory using ::operator new() and then it initializes an object of MyClass class in that memory using a constructor with the parameter *this .

#include <iostream>

class A {
    public:
        int m_value; 
        A(int value): m_value(value){};
};

int main (){

    int *a  = new int; 

    auto cb= new A(1); 

    std::cout << *a << std::endl; 
    std::cout << b->m_value << std::endl; 
    printf("%02x ", *b);

}

Program returned: 
0
15
0f

As you can see, the new for the a variable creates only a pointer that is value-initialized to 0. That's why when we dereference it we have 0 (all bit all 0, int is 4 bytes most of the time and the pointer point to a memory content = to 0x0000)

But for the b variable we pass parameters. And if we look at the memory content of the b object we can read 0f which means it contains 15 (the member value)

This is not new taking arguments, it's the constructor taking arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM