简体   繁体   中英

Declare an object in C++ w/o creating it?

Is this possible? For example if i write

Car myCar;

Then the constructor taking no arguments of Car is called. It results in an error if there is only a constructor taking arguments.

In Java I can easily declare an object and create it later using the exact same statement as above.

Well you confusing, in Java everything is a reference( or even you can think of like pointers) to objects and not the objects themself. So you probably what to do like this:

Car* car = NULL;

and then later explicitly call a c'tor by:

car = new Car( params...);

and don't forget to call delete after you finish using car object.

delete car;

若要执行您在Java中所做的操作,请在C ++中声明一个指针:

Car* myCar;

No, this is not possible. You could come up with some dirty hacks based on placement new which may get you close, but I doubt you are interested in them.

Why do you want to do that? Perhaps there is some clean way how to achieve that in a C++ style.

If you only want to create a variable which will point to some object later, this is what pointers are used for in C++.

auto_ptr<Car> car;

car = new Car(xxx);

Or "old way":

Car *car = NULL;

car = new Car(xxx);

delete car;

To find an item in a vector a code like this is commonly used:

std::vector <Car> cars;
Car *find = NULL;
for(std::vector<Car>::iterator car = cars.begin(); car != cars.end(); ++car )
for (int i=0; i<cars.size(); i++)
  if (Match(*car,xxx)
  {
    find=car;
    break;
  }

In many situations you would probably also prefer not to have a vector of cars, but of pointers to cars as well.

What you're used to in java isn't declaring the object and creating it later, but declaring the reference and creating the object to which the reference refers later. In C++, what you're looking for is:

Car *MyCar;
MyCar = new Mycar;

You could also use pointers, eg

Car *myCar;

Later you'd write:

myCar = new Car();

As discussed, the literal way to represent java-objects in C++ is by using pointers to class objects.

Using C++ pointers with the new statement has the disadvantage, that the slower heap has to be accessed, and that deleting the object has to be done manually.

Depending on the scope, there are more C/C++ like solutions.

At global or namespace-scope, you can use the extern-specifier to declare an object, defined elsewhere:

extern C c;
<more code>
c(1,2,3);

(The extern keyword tends to be used rarely within C++).

As usual, boost offers an elegant and general solution with the library boost::optional .

This can be used everwhere as follows:

optional<int> oa; // declaration
<more code> 
*oa=3; // construction

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