开发者

What's wrong with the "new" keyword in C++?

开发者 https://www.devze.com 2023-02-04 23:41 出处:网络
I know that this might sound like a stupid question, but why do I get an error which says something like \"

I know that this might sound like a stupid question, but why do I get an error which says something like "

cannot convert Object* to Object

" when I try to instantiate a new Object by using the statemen开发者_JAVA百科t "

Object obj = new Object();

"?

Am I to understand that the "new" keyword is reserved for pointers? Or is it something else?


Object* obj = new Object();

new always return pointer to object.

if you write just Object obj it means that obj will hold the object itself. If it is declared this way inside function then memory will be allocated on stack and will be wiped once you leave that function. new allocates memory on heap, so the pointer can be returned from function. Note that pointer can also point to local (stack) variable also.


Since new returns a pointer, you ought to use

Object *obj = new Object();


Exactly. New creates an object on the heap, and returns a pointer to it.


Object obj;

is all you need. It creates the object obj.


the new operator makes a pointer to a object

there for Object *obj = new Object() should work.

but just Object obj() constructs the object just fine but in stack space


I would have simply left a comment, but apparently I need a certain rep to do so.

In Java, variables used to store Objects are implicitly pointers to the Object. So new works the same way in C++ as Java, but you're not made aware of it in Java. I am going to guess that's the reason for your confusion.

0

精彩评论

暂无评论...
验证码 换一张
取 消