132 字
1 分钟
Consolidation6 Program's Output
What will be the output of the following C++ program?
#include <iostream>using namespace std;class A{public: A(){ cout<<"Constructor called\n"; } ~A(){ cout<<"Destructor called\n"; }};int main(int argc, char const *argv[]) { A *a = new A[4]; delete[] a; return 0;}Code behavior
A *a = new A[4];- This dynamically allocates an array of 4 objects of class
A. - The constructor is called once for each object, in order.
delete[] a;- This deletes the array.
- The destructor is called once for each object, in reverse order.
Order of calls
-
Constructors (called 4 times):
- Object 1
- Object 2
- Object 3
- Object 4
-
Destructors (called 4 times, reverse order):
- Object 4
- Object 3
- Object 2
- Object 1
Output
Constructor calledConstructor calledConstructor calledConstructor calledDestructor calledDestructor calledDestructor calledDestructor calledKey Concept (Exam Tip)
new[]→ constructor called for each elementdelete[]→ destructor called for each element in reverse order
Consolidation6 Program's Output
https://mizuki.anka2.top/posts/l5-cpp-week12-lecture/consolidation6-program/ 部分信息可能已经过时









