CKTIS / C++
Stack versus heap: automatic storage duration and dynamic allocation
C++23 specifies storage duration and object lifetime rules, not physical placement. An automatic object can contain a `std::string` that dynamically allocates character storage.
Version: ISO C++23; implementation support may vary
Syntax
struct Record { std::string text; };
std::unique_ptr<Record> owner;
{
Record local{"abc"};
owner = std::make_unique<Record>();
} // local is destroyed; the Record owned by owner remains alive
owner.reset(); // destroys the owned Record and releases its storageThe phrase “stack versus heap” is shorthand for a common implementation, not a physical layout guaranteed by C++23. Storage duration describes how long an object's storage can remain available at a minimum; it is not the same as the object's lifetime. An ordinary block variable declared without static, thread_local, or extern has automatic storage duration. If its object was constructed, it is destroyed when control leaves the block, including during exception unwinding.
std::make_unique<Record>() creates a separate Record with dynamic storage duration. The local owner can itself have automatic storage duration, while the object it manages can outlive the block that created it. When owner is destroyed, its default deleter destroys the object it still owns and releases its storage. This is RAII: the owner object manages the resource. Do not return a pointer or reference to a local object that will be destroyed when the function returns.
The text member is a std::string subobject with the same storage duration as its enclosing Record. Storage for the characters is a separate matter: the string uses its allocator as needed. An implementation may store short strings inside the string object (SSO), but C++23 guarantees neither that optimization nor a threshold for it. An automatic Record therefore does not imply zero dynamic allocations.
Examples
#include <iostream>
#include <memory>
#include <string>
struct Record {
std::string text;
};
int main() {
std::unique_ptr<Record> owner;
{
Record local{"abc"};
owner = std::make_unique<Record>();
owner->text = "hello";
std::cout << "local: " << local.text.size() << '\n';
}
std::cout << "owned: " << owner->text.size() << '\n';
}
Result
local: 3 owned: 5
`local` is destroyed when the inner block exits. The second line can still be printed because `owner` owns the other `Record` until `main` ends. The output does not show physical placement or allocation counts.
Related lessons
- C++ · Lesson 22 · Advanced · Version: 3