c++构造函数
The difference between the two lines:
lies in where the objects are allocated (stack vs. heap) and how their lifetime is managed. Here's a detailed breakdown:
1. Stack Allocation (MyClass obj1(10);
)
- Memory Location:
obj1
is created on the stack. - Lifetime: The lifetime of
obj1
is tied to its scope. It will be automatically destroyed when it goes out of scope (in this case, when the current function, such asmain()
, finishes execution). - Performance: Stack allocation is generally faster than heap allocation because memory allocation and deallocation are done automatically by the compiler. The memory is managed with simple push/pop operations.
- No Need to Manually Free: Since
obj1
is on the stack, you do not need to manually free the memory. It will be cleaned up automatically when the function scope ends.
Example:
2. Heap Allocation (MyClass* obj5 = new MyClass(10);
)
- Memory Location:
obj5
is created on the heap. Thenew
operator dynamically allocates memory for the object, and it returns a pointer to the allocated object. - Lifetime: The lifetime of the object is not tied to the scope. The object will remain alive until you explicitly call
delete
to free the allocated memory. - Memory Management: You must manually manage the memory using
delete
to avoid memory leaks. If you forget to calldelete
, the memory used by the object will not be freed, causing a memory leak.
Example:
Key Differences:
Feature | Stack Allocation (MyClass obj1(10); ) |
Heap Allocation (MyClass* obj5 = new MyClass(10); ) |
---|---|---|
Memory Location | Stack | Heap |
Lifetime | Tied to the scope (automatic cleanup) | Manually managed (must use delete to free memory) |
Performance | Faster allocation/deallocation | Slower due to dynamic allocation and deallocation |
Memory Management | Automatic (no need for delete ) |
Manual (delete needed to free memory) |
Object Type | The object is created directly, not a pointer | A pointer to the dynamically allocated object is created |
When to Use Each:
-
Stack Allocation: Use when you don't need the object to live beyond the scope of the function (i.e., when it’s temporary or local to a function). It's simpler and avoids memory management headaches.
Example use case: Temporary variables, small objects, etc.
-
Heap Allocation: Use when you need an object to live beyond the function scope or when you don't know the exact number of objects you need at compile time (e.g., dynamic arrays, objects that need to persist until explicitly deleted).
Example use case: Objects that need to be shared across functions or require dynamic memory allocation.
Summary:
MyClass obj1(10);
: Objectobj1
is created on the stack. It is automatically destroyed when it goes out of scope.MyClass* obj5 = new MyClass(10);
: A pointerobj5
points to an object on the heap. The object must be manually deleted usingdelete
when you are done with it, or it will cause a memory leak.
In practice, stack allocation is usually preferred for simplicity and efficiency unless you have specific reasons to allocate objects dynamically on the heap.
Summary of Initialization Methods:
- Constructor with parameters:
People person("Alice", 30);
- Default constructor:
People person;
- Brace (uniform) initialization:
People person{"Alice", 30};
- Pointer and
new
:People* person = new People("Alice", 30);
- Aggregate initialization:
People person = {"Alice", 30};
memset
(not recommended for complex objects):memset(&person, 0, sizeof(People));
initializer_list
constructor:People person{"Alice", "30"};
- Copy constructor:
People copy = original;
- Move constructor:
People moved = std::move(original);
- Smart pointers (
std::make_unique
,std::make_shared
):auto person = std::make_unique<People>("Alice", 30);
- Container initialization (
std::vector
):std::vector<People> people = { People("Alice", 30), People("Bob", 25) };
- Assignment after initialization:
People person; person.name = "Alice"; person.age = 30;
- Using
std::tuple
:People person(std::get<0>(data), std::get<1>(data));
Each of these methods provides different advantages depending on the context in which you're working.