c++构造函数

 

The difference between the two lines:

cpp
MyClass obj1(10); // Stack-allocated object MyClass* obj5 = new MyClass(10); // Heap-allocated object

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 as main(), 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:

cpp
void example() { MyClass obj1(10); // obj1 is created on the stack // obj1 will be destroyed automatically when it goes out of scope (end of example() function) }

2. Heap Allocation (MyClass* obj5 = new MyClass(10);)

  • Memory Location: obj5 is created on the heap. The new 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 call delete, the memory used by the object will not be freed, causing a memory leak.

Example:

cpp
void example() { MyClass* obj5 = new MyClass(10); // obj5 points to an object created on the heap // obj5 will remain alive until you manually delete it delete obj5; // You need to manually free the memory }

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);: Object obj1 is created on the stack. It is automatically destroyed when it goes out of scope.
  • MyClass* obj5 = new MyClass(10);: A pointer obj5 points to an object on the heap. The object must be manually deleted using delete 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:

  1. Constructor with parameters: People person("Alice", 30);
  2. Default constructor: People person;
  3. Brace (uniform) initialization: People person{"Alice", 30};
  4. Pointer and new: People* person = new People("Alice", 30);
  5. Aggregate initialization: People person = {"Alice", 30};
  6. memset (not recommended for complex objects): memset(&person, 0, sizeof(People));
  7. initializer_list constructor: People person{"Alice", "30"};
  8. Copy constructor: People copy = original;
  9. Move constructor: People moved = std::move(original);
  10. Smart pointers (std::make_unique, std::make_shared): auto person = std::make_unique<People>("Alice", 30);
  11. Container initialization (std::vector): std::vector<People> people = { People("Alice", 30), People("Bob", 25) };
  12. Assignment after initialization: People person; person.name = "Alice"; person.age = 30;
  13. 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    
posted @   ChuckLu  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用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
点击右上角即可分享
微信分享提示