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.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2023-02-20 2023-02-19,新的30道Vue面试题!
2022-02-20 Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable
2020-02-20 HearthBuddy combo
2019-02-20 Model Validation in ASP.NET Web API
2019-02-20 Environment.NewLine
2019-02-20 What's the difference between SDK and Runtime in .NET Core?
2019-02-20 The current .NET SDK does not support targeting .NET Core 3.0