/game-porting-skills:managing-metal-cpp-lifetimesfrom game-porting-skills
Guides correct ownership, retain/release, and autorelease pool placement for metal-cpp objects. Use when porting from ARC or debugging crashes, leaks, or use-after-free.
Ships in game-porting-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
metal-cpp types like MTL::Buffer* wrap ObjC Metal objects, so the underlying ObjC retain/release rules still apply. Getting ownership wrong causes leaks, use-after-free, or double-free.
Methods starting with new, alloc, copy, mutableCopy, or Create return owned (+1) objects. Everything else returns autoreleased objects.
Returned from new/alloc/copy/mutableCopy/Create?
YES → NS::TransferPtr(ptr) // you already own it
NO → need AutoreleasePool in scope
Want to keep beyond pool scope?
YES → NS::RetainPtr(ptr) // retains; survives pool drain
NO → use raw pointer // pool drains it
| API Pattern | Returns | Wrap With |
|---|---|---|
device->new*() | Owned | NS::TransferPtr() |
alloc()->init() | Owned | NS::TransferPtr() |
*CommandEncoder() | Autoreleased | Raw pointer within pool scope |
::descriptor() / ::string() | Autoreleased | NS::RetainPtr() if keeping |
MTL::CreateSystemDefaultDevice() | Owned | NS::TransferPtr() |
NS::TransferPtr(ptr) — Takes ownership without additional retain. For objects you already own.NS::RetainPtr(ptr) — Takes ownership with additional retain. For autoreleased objects you want to keep beyond pool scope.Pools are required in these contexts — without them, autoreleased objects accumulate indefinitely:
drain() releases contents)// Frame pool — create once, drain per frame
auto framePool = NS::TransferPtr(NS::AutoreleasePool::alloc()->init());
// ... each frame:
framePool->drain(); // releases autoreleased objects, pool stays alive for reuse
drain() releases contents but keeps the pool alive. reset() on the SharedPtr destroys the pool.
When porting a project that has ARC translation units alongside metal-cpp, use bridge casts to hand ownership across the boundary:
| Cast | Effect | Use When |
|---|---|---|
(__bridge T) | No retain/release | Temporary access, no ownership change |
(__bridge_retained T) | +1 retain | Handing an owned object to metal-cpp — wrap result in NS::TransferPtr |
(__bridge_transfer T) | C++ releases its +1 | Handing back to ARC from a metal-cpp +1 object |
A __bridge_retained cast produces a +1 object suitable for NS::TransferPtr. Every __bridge_retained must be balanced by a __bridge_transfer or explicit release().
NS::SharedPtr copy across threads is safe (atomic retain)MTL4::CommandBuffer does not retain resources. MTL::CommandBuffer retains by default but can be configured via its descriptor to not retain. When resources are not retained by the command buffer, you must keep them alive (via SharedPtr, deferred destruction queue, or residency set) until the GPU is done with them — a fence or event signals completion. The deferred destruction queue pattern is canonicalised in managing-metal4-resources (frame-delayed release with mutex-protected residency removal).
release() on an autoreleased object — Autoreleased objects (encoders, descriptors, etc.) are released when the pool drains. An explicit release() causes a double-free.TransferPtr on autoreleased object — TransferPtr calls release() on destruction → same double-free as above. Use RetainPtr if you need to keep it past pool scope, otherwise raw pointer within scope.OBJC_DEBUG_MISSING_POOLS=YES — runtime warning when no pool exists on current threadleaks --autoreleasePools — inspect pool contents in a memgraphMTL_HUD_ENABLED=1) — continuously growing memory counter = resource leakRead the relevant metal-cpp header before writing lifetime code — the headers are the source of truth for the ownership helpers and their exact semantics.
Foundation/NSSharedPtr.hpp (NS::SharedPtr, NS::TransferPtr, NS::RetainPtr), Foundation/NSAutoreleasePool.hpp (NS::AutoreleasePool)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub apple/game-porting-toolkit --plugin game-porting-skills24 skills in this plugin
/compiling-with-metal-shaderconverterALWAYS use when compiling DXIL/HLSL to metallib with Metal shader converter (commonly referred to as MSC) via the metal-shaderconverter CLI or libmetalirconverter (IRCompiler, IRObject, IRShaderReflection) at runtime. Covers offline/runtime DXIL compilation, root signatures, reflection output, ray tracing shaders, geometry/tessellation emulation compilation, framebuffer fetch in HLSL, programmable blending in HLSL, Metal_HLSL.inc, and compatibility flags. Do NOT trigger for binding compiled shaders to encoders — use integrating-metal-shaderconverter-shaders for that./creating-metal4-shader-pipelinesALWAYS use when creating Metal pipeline state objects with Metal 4 descriptors (MTL4RenderPipelineDescriptor, MTL4ComputePipelineDescriptor, MTL4MeshRenderPipelineDescriptor) via MTL4Compiler. Covers function descriptors, function constant specialization, flexible/unspecialized PSOs, color-attachment mapping, async compilation (MTL4CompilerTask), pipeline caching (MTL4Archive, MTL4PipelineDataSetSerializer), static/binary shader linking, and pipeline reflection. Do NOT trigger for HLSL/DXIL → metallib — use compiling-with-metal-shaderconverter./debugging-rendering-issuesALWAYS use when a user porting a game to Metal reports a rendering issue — blank screen, wrong output, or anything that looks incorrect on Metal vs. the source platform. Covers black screen, missing geometry, wrong colors, gamma/sRGB problems, texture artifacts, z-fighting, alpha blending, flickering, visual corruption, and upside-down/mirrored geometry. Works with or without a GPU trace. Do NOT trigger when the user just wants to inspect an existing .gputrace./integrating-metal-shaderconverter-shadersALWAYS use when integrating Metal shader converter (commonly referred to as MSC) shaders at runtime — binding model, top-level argument buffer (TLAB), root signature resource locations, descriptor/sampler heaps, static samplers, bindless resources, vertex fetch, separate stage-in, geometry/tessellation emulation, compute dispatch, unbounded arrays, and append/consume buffers. Do NOT trigger for compiling DXIL/HLSL to metallib — use compiling-with-metal-shaderconverter for that./managing-metal4-resourcesALWAYS use when working with Metal 4 resources — buffer / texture / heap creation, storage modes, `MTLResidencySet` management, heap aliasing, purgeable state, texture view pools, GPU lossless compression, and deferred destruction. Trigger for MTLBuffer, MTLTexture, MTLHeap, MTLResidencySet, addAllocation, requestResidency, useResidencySet, addResidencySet, MTLStorageMode*, MTLPurgeableState, MTLTextureViewPool, MTLResourceViewPool, newTextureViewWithPixelFormat:, copyFromBuffer:toTexture:, "GPU fault on resource", "non-resident resource", heap aliasing. Do NOT trigger for TBDR architecture or Metal 3 → Metal 4 namespace tables — use `translating-to-metal4-api`. Barrier visibility / `MTL4VisibilityOption*` / render-pass transition barriers — use `managing-metal4-synchronization`. `CAMetalLayer.residencySet` — use `presenting-metal-drawables`. `NS::SharedPtr` / autorelease pool / ARC bridging — use `managing-metal-cpp-lifetimes`./managing-metal4-synchronizationMetal 4 explicit synchronization — barriers, fences, events, and cross-API state translation (from D3D12, Vulkan, OpenGL). Use when porting GPU synchronization, translating resource state transitions, or debugging barrier-related visual corruption.Other plugins' skills for the same job