简体   繁体   中英

C++ Heap Object has Stack or Heap Members?

If I allocate a new object on the heap, are all variables defined within the class of the object also on the heap?

For example, say I have a Node class that has an x, y, z coordinate held within an array called _pos. For the sake of the user creating many Node objects, Node is declared on the heap as:

Node n = new Node(0, 0, 0);

Should I also declare the position array on the heap as:

class Node {
public:
  Node(double x, double y, double z) {
    _pos = new double[3] {x, y, z};
  }

private:
  double* _pos;
}

Or is the _pos array already considered on the heap and the following works as well

class Node {
public:
  Node(double x, double y, double z) {
    _pos = double[3] {x, y, z};
  }

private:
  double* _pos;
}

I'm guessing the second one is also considered on the heap, in which case it also makes deallocation a bit easier, but I'm hoping someone can confirm.

If I allocate a new object on the heap, are all variables defined within the class of the object also on the heap?

Yes.

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