You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中Student std[2]与Student* std = new Student[2]的区别

Difference between Student std[2]; and Student* std = new Student[2]; in C++

Great question! These two lines might seem like they do the same thing at first, but they have critical differences in how memory is managed, where objects live, and their lifecycle. Let's break it all down clearly:

1. Where the Memory Lives

  • Student std[2]; creates an array on the stack. Stack memory is small, automatically managed by the compiler, and tied to the scope (like a function or code block) where the array is declared.
  • Student* std = new Student[2]; allocates an array on the heap. Heap memory is much larger, but it's not tied to any scope—you're in charge of managing it.

2. Lifecycle & Automatic Cleanup

  • Stack array: As soon as the scope containing std[2] ends (e.g., when the function returns), the compiler automatically calls the destructor for each Student object and reclaims the stack memory. No extra work needed from you.
  • Heap array: The array stays in memory until you explicitly free it with delete[] std;. If you forget this, you'll get a memory leak—the memory will stay allocated until your program exits. Even worse, if an exception is thrown before you call delete[], you might never get the chance to clean it up (smart pointers like std::unique_ptr<Student[]> can fix this, but that's an advanced tweak).

3. Memory Management Responsibility

  • Stack array: Zero work on your end. The compiler handles allocation and cleanup entirely.
  • Heap array: You have to track when the array is no longer needed and call delete[] to release it. Mismanaging this is one of the most common C++ pitfalls.

4. Accessing Class Members (Spoiler: It's the Same!)

Here's a nice surprise—you access class members exactly the same way for both:

  • Use std[0].name (or any index) to access members of a specific object in the array.
  • For the first element, you can also use std->name (since the stack array's name implicitly converts to a pointer to its first element, just like the heap array's pointer variable).

The only under-the-hood difference is that std in the stack case is an array type (Student[2]), while in the heap case it's a raw pointer (Student*). But for day-to-day member access, the syntax is identical.

5. Initialization Behavior

  • Stack array: If Student has a default constructor, it will be called for each element. If Student doesn't have a default constructor, this line will fail to compile. For POD (Plain Old Data) types, the array will be default-initialized (meaning it might hold garbage values) unless you use brace initialization: Student std[2]{}; (C++11 and later).
  • Heap array: Same rule for default constructors—you need one for new Student[2] to work. To ensure proper initialization (instead of leaving garbage for POD types), you can use new Student[2](); (pre-C11) or new Student[2]{}; (C11+).

Quick Example to See It in Action

Let's use a simple Student class to demonstrate the lifecycle differences:

#include <iostream>
#include <string>

class Student {
public:
    std::string name;
    Student() { std::cout << "Default constructor called\n"; }
    ~Student() { std::cout << "Destructor called for " << name << "\n"; }
};

int main() {
    // Stack array
    std::cout << "=== Stack Array ===\n";
    Student stackStudents[2];
    stackStudents[0].name = "Alice";
    stackStudents[1].name = "Bob";

    // Heap array
    std::cout << "\n=== Heap Array ===\n";
    Student* heapStudents = new Student[2];
    heapStudents[0].name = "Charlie";
    heapStudents[1].name = "Diana";
    delete[] heapStudents; // Critical: Don't skip this!

    std::cout << "\n=== End of main() ===\n";
    return 0;
}

When you run this, you'll see:

  • The stack array's destructors run after the "End of main()" line (when the scope ends).
  • The heap array's destructors run right after delete[] is called.

内容的提问来源于stack exchange,提问作者Arvind Dexter Thillainathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:13:08