简体   繁体   中英

C++ Pointers and Object Instantiation

This works:

MyObject *o;
o = new MyObject();

And this does not:

MyObject o = new MyObject();

Why?

The keyword new returns a pointer . It must be assigned to a pointer of an object.

This would also work:

MyObject o = MyObject();

EDIT:

As Seth commented, the above is equivalent to:

MyObject o;

The default constructor (ie without parameters) is called if no constructor is given.

Because they're not equivalent. Try:

 MyObject* o = new MyObject();

new MyObject() returns a pointer to an object of type MyObject . So really you are trying to assign an object MyObject* (yes, a pointer can be considered an object, too). Thus, you have to declare a variable of MyObject* or something compatible like std::shared_ptr<MyObject> .

The proper initialisation is

// in C++03
MyObject* o(new MyObject());

// in C++11
MyObject* o {new MyObject()};

While the assignment

MyObject* o = new MyObject();

is valid as well.

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