Unreal C++ Idioms
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Unreal C++ looks like ordinary C++ until the first line you copy from the standard library does not compile, or compiles and crashes the garbage collector. The engine has its own containers, strings, smart pointers, delegates, logging and assertions, and a coding standard that makes all of them read alike. Learning those idioms is most of the work of becoming fluent: the language is the same, the vocabulary is Epic’s.
The facts were checked in November 2026 against the Unreal Engine 5.8 documentation (5.8 was released on 2026-06-17; the latest hotfix at the time of writing is 5.8.4). The examples compile in a C++ project with the module Bookshelf (API macro BOOKSHELF_API, log category LogBookshelf) on any platform Unreal builds for. They continue the running example of the other pages: ABookActor, AShelfActor, ABookshelfGameState and ABookshelfPlayerController, with the shared model bookshelf.glb. The reflection macros are in UObject, Reflection and Garbage Collection; the plain-language C++ features are in the C++ section.
Naming and the coding standard
Epic’s coding standard is mandatory inside Epic and the model for everyone else; the Unreal Header Tool also enforces the class prefixes. The names follow PascalCase with no underscores in type and function names, and U.S. English spelling.
| Prefix | Used for | Bookshelf example |
|---|---|---|
|
Template classes. |
|
|
Classes that inherit from |
|
|
Classes that inherit from |
|
|
Classes that inherit from |
|
|
Abstract interface classes. |
|
|
Enums. |
|
|
Most other classes and structs. |
|
|
Boolean variables, as a prefix. |
|
The rest of the standard that matters in daily code:
-
Methods are verbs; booleans ask questions.
GetDisplayTitle(),IsHeld(). Avoid vague verbs such asHandleandProcess. A by-reference output parameter is prefixedOut(OutResult). -
Portable types. Use
int8,uint8,int16,int32,int64and their unsigned forms,floatanddouble. Use explicitly sized types for serialized and replicated data; plainintonly when the width does not matter. The character type isTCHAR. -
nullptr, neverNULL.overrideandfinalon virtual overrides (write bothvirtualandoverride). -
consteverywhere it applies: parameters passed by const reference or pointer, methods that do not modify the object, iteration that does not modify the container. Neverconston a by-value return type. -
enum class, not namespaced enums, withENUM_CLASS_FLAGSfor bit flags. An enum exposed to Blueprint must beuint8. -
autois avoided, so that the type stays visible to the reader. It is allowed to bind a lambda, for very long iterator types and in template-heavy code; structured bindings are not allowed. -
Braces on their own line, always, even for one statement; tabs of width four for indentation;
switchstatements end every case and have adefault. -
Pass
UObjecttypes by pointer, not by reference, so that a null is representable. -
Avoid boolean flag parameters; use an enum or a parameter struct for long argument lists. Members are private by default.
-
Headers use
#pragma once, forward declarations where possible and include only what they need ("include what you use"). -
New engine APIs live in a
UE::namespace. Never put ausingdeclaration at global scope and never put a namespace around aUCLASSorUSTRUCT. -
Prefer Unreal containers and strings to the standard library ones; the standard library is for interop code. The standard
<atomic>,<type_traits>and<cmath>headers are fine. -
Comments say why, in JavaDoc style on the declaration; self-documenting names first.
Source: Epic: Coding Standard
Strings: FString, FName and FText
Unreal has three string types because a string can mean three different things.
| Type | What it is | Use it for |
|---|---|---|
|
A mutable character array. It can be searched, modified and compared, and every instance stores its own characters. |
Building text, parsing, file paths, anything you manipulate. |
|
A lightweight, immutable identifier. A global table stores each unique string once; an |
Asset names, bone and socket names, material parameter names, gameplay identifiers. |
|
The localization type: it carries a namespace and key so that translators can replace it, and it formats numbers, dates and plural forms for the user’s culture. |
Everything the player reads: titles, labels, dialogue. |
String literals are wrapped in TEXT("Book") so that they are stored as TCHAR (the native Unicode type) with no conversion; without it a literal is ANSI and must be converted. FString::Printf builds a string with printf-style formats, and FText::Format builds localized text from a pattern with {0} style or named placeholders. Mark user-facing literals with LOCTEXT (inside a namespace you define) or NSLOCTEXT; INVTEXT and AsCultureInvariant make text that must not be localized, such as a name from an external source.
| Conversion | How |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
No direct conversion; go through |
|
|
|
|
The * in *Str is a dereference operator that FString overloads to return the TCHAR pointer; you will write it constantly, because UE_LOG and Printf take TCHAR pointers for %s.
Source: Epic: String Handling
Containers: TArray, TMap and TSet
The three Unreal containers replace std::vector, std::unordered_map and std::unordered_set, with names, move semantics and garbage-collector support of their own.
-
TArray is a contiguous, resizable array.
AddandPushcopy or move an element in,Emplaceconstructs in place,AddUniquerefuses duplicates,Insertplaces at an index,Appendadds many.Removeerases every equal element,RemoveSinglethe first,RemoveAtby index (checkIsValidIndexfirst), andRemoveAlltakes a predicate; theSwapvariants are faster but do not keep order. Search withContains,Find(an index orINDEX_NONE),FindByKeyandFindByPredicate(a pointer ornullptr).SortandHeapSortare unstable;StableSortkeeps the order of equal elements. The unused capacity is called slack;Reset(n)andEmpty(n)request it andShrinkreleases it. The pointer fromGetDatais valid only until the next mutating operation. -
TMap stores key-value pairs. A key needs
operator==and aGetTypeHashoverload (or custom key functions).Addreplaces the value of an existing key;TMultiMapallows duplicate keys.Findreturns a pointer to the value ornullptrand does one lookup.FindRefreturns a copy or a default value without adding anything,FindOrAddreturns a reference after inserting a default, andoperator[]asserts when the key is missing. Iteration order is not reliable, elements are not contiguous, and growth can invalidate pointers and references to elements. -
TSet stores unique elements, where the element is its own key.
Add,Contains,RemoveandFindbehave as above; iteration order is unspecified.
A UPROPERTY container of UObject pointers is how the garbage collector learns that the objects are in use; a plain member TArray<ABookActor*> is invisible to it. The collection below keeps the books in an array, counts copies per title in a map and tracks lending in a set.
// BookCatalog.h
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "BookCatalog.generated.h"
class ABookActor;
UCLASS()
class BOOKSHELF_API UBookCatalog : public UObject
{
GENERATED_BODY()
public:
/** Adds a book to the catalog. Ignores nullptr after reporting it. */
void Register(ABookActor* Book);
/** Lends one copy. Returns false when the title is unknown or already lent. */
bool CheckOut(FName BookId);
int32 GetCopies(FName BookId) const;
FText Describe(FName BookId) const;
/** Drops destroyed books and orders the rest by title. */
void Tidy();
private:
/** A UPROPERTY, so the garbage collector sees the references. */
UPROPERTY()
TArray<TObjectPtr<ABookActor>> Books;
TMap<FName, int32> Copies;
TSet<FName> CheckedOut;
};
// BookCatalog.cpp
#include "BookCatalog.h"
#include "BookActor.h"
#include "Internationalization/Text.h"
#include "Bookshelf.h"
#define LOCTEXT_NAMESPACE "Bookshelf"
void UBookCatalog::Register(ABookActor* Book)
{
// ensureMsgf reports once to the crash reporter and lets the game continue.
if (!ensureMsgf(IsValid(Book), TEXT("UBookCatalog::Register received a null or destroyed book")))
{
return;
}
Books.AddUnique(Book);
// FName is case-insensitive and cheap to compare, so it makes a good key.
const FName BookId(*Book->GetDisplayTitle().ToString());
int32& Count = Copies.FindOrAdd(BookId);
++Count;
}
bool UBookCatalog::CheckOut(FName BookId)
{
const int32* Count = Copies.Find(BookId);
if (Count == nullptr || *Count <= 0 || CheckedOut.Contains(BookId))
{
return false;
}
CheckedOut.Add(BookId);
UE_LOG(LogBookshelf, Log, TEXT("%s checked out"), *BookId.ToString());
return true;
}
int32 UBookCatalog::GetCopies(FName BookId) const
{
return Copies.FindRef(BookId);
}
FText UBookCatalog::Describe(FName BookId) const
{
FFormatNamedArguments Args;
Args.Add(TEXT("Title"), FText::FromName(BookId));
Args.Add(TEXT("Copies"), GetCopies(BookId));
return FText::Format(LOCTEXT("CatalogLine", "{Title}: {Copies} copies"), Args);
}
void UBookCatalog::Tidy()
{
Books.RemoveAll([](const TObjectPtr<ABookActor>& Book)
{
return !IsValid(Book);
});
Books.Sort([](const TObjectPtr<ABookActor>& A, const TObjectPtr<ABookActor>& B)
{
return A->GetDisplayTitle().CompareTo(B->GetDisplayTitle()) < 0;
});
}
#undef LOCTEXT_NAMESPACE
Delegates
A delegate is a type-safe, serializable-or-not function pointer with a binding list, Unreal’s version of the observer pattern (compare a C# event). Epic documents three kinds, and each is available in single-cast and multicast form.
| Kind | Declared with | Properties |
|---|---|---|
Single-cast |
|
At most one binding; may return a value and may be |
Multicast |
|
Many bindings, no return value, undefined call order. Fire with |
Dynamic |
|
Serializable and reflected: bound functions are found by name and must be |
Signatures allow up to eight parameters and, for single-cast kinds, up to four payload values passed at bind time. Declarations may sit at global scope, in a namespace or inside a class, not inside a function body. A delegate type carries the F prefix, and by convention ends in a name that describes the moment (FOnScoreChangedNative).
The binding function chooses how safe the binding is:
-
BindUObjectandAddUObjectkeep a weak reference to aUObject; a destroyed object is skipped.BindSPandAddSPdo the same for aTSharedPtrowner (not thread-safe). -
BindRawandAddRawstore a raw pointer with no lifetime tracking. Executing after the object is deleted is undefined behaviour; avoid them forUObject. -
BindLambdaandAddLambdastore a functor, and are safe only when the lambda captures nothing that can die.BindWeakLambdaandAddWeakLambdatake aUObjectand run the lambda only while it is alive;AddSPLambdadoes the same for a shared pointer. -
BindStaticandAddStaticbind a free or static function.
Delegates are safe to copy but allocate when passed by value, so pass them by reference. Never read the return value of an unbound delegate: Execute on an unbound single-cast delegate asserts, and an unbound delegate with output parameters can leave them uninitialized, so test with IsBound or use ExecuteIfBound when there is no return value.
// BookshelfGameState.h (excerpt)
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameStateBase.h"
#include "BookshelfGameState.generated.h"
DECLARE_MULTICAST_DELEGATE_OneParam(FOnScoreChangedNative, int32 /*NewScore*/);
UCLASS()
class BOOKSHELF_API ABookshelfGameState : public AGameStateBase
{
GENERATED_BODY()
public:
void AddScore(int32 Delta);
int32 GetScore() const { return Score; }
/** Native listeners (C++ only). Blueprints use a dynamic delegate instead. */
FOnScoreChangedNative OnScoreChanged;
protected:
UPROPERTY(BlueprintReadOnly, Category = "Bookshelf")
int32 Score = 0;
};
// BookshelfPlayerController.h (excerpt)
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "BookshelfPlayerController.generated.h"
class ABookshelfGameState;
UCLASS()
class BOOKSHELF_API ABookshelfPlayerController : public APlayerController
{
GENERATED_BODY()
protected:
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
private:
void HandleScoreChanged(int32 NewScore);
TWeakObjectPtr<ABookshelfGameState> WatchedState;
FDelegateHandle ScoreHandle;
};
// BookshelfGameState.cpp and BookshelfPlayerController.cpp (excerpts)
void ABookshelfGameState::AddScore(int32 Delta)
{
Score += Delta;
OnScoreChanged.Broadcast(Score);
}
void ABookshelfPlayerController::BeginPlay()
{
Super::BeginPlay();
if (ABookshelfGameState* State = GetWorld()->GetGameState<ABookshelfGameState>())
{
WatchedState = State;
ScoreHandle = State->OnScoreChanged.AddUObject(this, &ABookshelfPlayerController::HandleScoreChanged);
// A second listener that disappears with this controller. The weak lambda is
// skipped once 'this' has been destroyed.
State->OnScoreChanged.AddWeakLambda(this, [this](int32 NewScore)
{
UE_LOG(LogBookshelf, Verbose, TEXT("%s saw score %d"), *GetName(), NewScore);
});
}
}
void ABookshelfPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
if (ABookshelfGameState* State = WatchedState.Get())
{
State->OnScoreChanged.Remove(ScoreHandle);
}
Super::EndPlay(EndPlayReason);
}
void ABookshelfPlayerController::HandleScoreChanged(int32 NewScore)
{
UE_LOG(LogBookshelf, Log, TEXT("Score changed to %d"), NewScore);
}
A single-cast delegate is the right tool for "ask exactly one party a question". The shelf asks whichever rule is bound whether a book may be shelved:
// ShelfActor.h (excerpt)
DECLARE_DELEGATE_RetVal_OneParam(bool, FCanShelveBook, const ABookActor* /*Book*/);
// In the class body:
FCanShelveBook CanShelveRule;
// ShelfActor.cpp (excerpt)
bool AShelfActor::IsBookAllowed(const ABookActor* Book) const
{
// Execute on an unbound delegate would assert, so test first.
return !CanShelveRule.IsBound() || CanShelveRule.Execute(Book);
}
// Binding elsewhere, for example in the game mode:
Shelf->CanShelveRule.BindLambda([](const ABookActor* Book)
{
return IsValid(Book);
});
The Epic standard adds rules for lambdas: keep them short, capture explicitly instead of [&] or [=], never capture locals or members by reference for deferred execution, and do not let this or a UObject pointer hide in a capture that the garbage collector cannot see. For deferred execution use CreateWeakLambda or AddWeakLambda (which unbind when the object dies), or capture a TWeakObjectPtr and validate it inside.
Logging
UE_LOG takes a category, a verbosity and a TEXT format. Declare one category per module so that you can filter and raise its verbosity independently. In the header, below the includes, use DECLARE_LOG_CATEGORY_EXTERN(Name, DefaultVerbosity, CompileTimeVerbosity); in one source file, DEFINE_LOG_CATEGORY(Name).
// Bookshelf.h
#pragma once
#include "CoreMinimal.h"
DECLARE_LOG_CATEGORY_EXTERN(LogBookshelf, Log, All);
// Bookshelf.cpp
#include "Bookshelf.h"
#include "Modules/ModuleManager.h"
DEFINE_LOG_CATEGORY(LogBookshelf);
IMPLEMENT_PRIMARY_GAME_MODULE(FDefaultGameModuleImpl, Bookshelf, "Bookshelf");
| Verbosity | Behaviour |
|---|---|
|
Always printed, then crashes the session. |
|
Printed to the console and the log; shown in red. |
|
Printed to the console and the log; shown in yellow. |
|
Printed to the console and the log; shown in grey. |
|
Written to the log only. |
|
Not printed by default; appear only when enabled for the category. Use them for detailed traces. |
Raise verbosity without recompiling: type log LogBookshelf verbose in the console, or start the game with -LogCmds="LogBookshelf Verbose" (an all category sets every category at once). Format values with %s for strings (pass an FString as *Name), %d for integers and %f for floats; print a boolean by choosing between TEXT("true") and TEXT("false").
UE_LOGFMT (added in UE 5.2, header Logging/StructuredLog.h) is the structured form: a format with named placeholders and values that stay separate fields in the log, positional or named but never both in one call.
#include "Logging/StructuredLog.h"
void ABookActor::LogPull(const AActor* Puller) const
{
UE_LOGFMT(LogBookshelf, Log, "{Book} was pulled by {Puller}",
("Book", GetNameSafe(this)), ("Puller", GetNameSafe(Puller)));
if (GEngine)
{
// Key -1 adds a new message every call; use a fixed key to replace an existing one.
GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Yellow, TEXT("Book pulled"));
}
}
Source: Epic: Logging
Assertions: check, verify and ensure
| Macro | On failure | When it is active |
|---|---|---|
|
Halts execution. |
Debug and Development builds; compiled out of Test and Shipping unless |
|
Halts execution. |
Debug builds only. Use for expensive checks. |
|
Halts execution. |
Debug, Development, Test and Shipping Editor builds. The expression is always evaluated, so it may have side effects. |
|
Reports to the crash reporter once per session and continues. |
The expression is evaluated in all builds; reporting happens in Debug, Development, Test and Shipping Editor builds. |
|
As |
Same as |
Use check for conditions with no side effects, verify when the expression must run in every build, ensure for a recoverable error that you still want to hear about, and checkNoEntry for an impossible switch default. Never put a side effect inside check: the Shipping build removes it.
Source: Epic: Asserts
Safe pointers
IsValid(Object) is the correct test for a UObject pointer: it is false for nullptr and for an object that is pending destruction, which a plain null test misses. A TWeakObjectPtr observes an object without keeping it alive; call Get() and test the result. Use a UPROPERTY (or TObjectPtr member) for pointers that must keep an object alive, and TSharedPtr and MakeShared for plain C++ objects that are not UObject. The garbage-collection rules and the full pointer family are on UObject, Reflection and Garbage Collection; the language-level equivalents are in C++ memory management and smart pointers.
Common mistakes
-
A raw
UObjectpointer member withoutUPROPERTY. The garbage collector does not see it, the object can be destroyed, and the pointer dangles. UseUPROPERTY()with aTObjectPtr, or aTWeakObjectPtrwhen you do not own the object. -
Using standard containers or
std::stringfor engine data. They do not integrate with garbage collection, serialization or Blueprint; use them only at interop boundaries. -
A literal without
TEXT.FString Name = "Book";compiles through a conversion; the standard requiresTEXT("Book"). -
Passing an
FStringto%swithout.* The format reads the object bytes as characters; always pass*Str. -
Using
FNamewhere text is shown to the player. AnFNameis case-insensitive and cannot be localized; showFText. -
Binding a raw pointer or a plain lambda to a delegate on an object that can die. Use
AddUObject,AddWeakLambdaor aTWeakObjectPtrguard. -
Forgetting
UFUNCTION()on anAddDynamictarget. It compiles and never fires. -
Executeon an unbound single-cast delegate. It asserts; testIsBoundor useExecuteIfBound. -
Never unbinding. A multicast delegate that outlives its listener leaks bindings; store the
FDelegateHandleand callRemove, or useRemoveAll(this)inEndPlay. -
Side effects inside
check. The expression disappears in Shipping; useverify. -
Indexing a
TMapwithoperator[]for a missing key. It asserts. UseFind, which returns a pointer ornullptr. -
Holding a pointer to a container element across an
Add. Growth reallocates and invalidates it. -
Relying on
TMaporTSetiteration order. It is unspecified.
Performance notes
-
TArrayis contiguous, so iteration and sorting are cache-friendly; prefer it toTMapfor small collections searched linearly, where hashing costs more than a scan.Reserve-like control comes fromReset(n)andEmpty(n): size an array once when the count is known to avoid repeated growth. -
Emplaceconstructs in place and avoids a temporary;RemoveSwapandRemoveAtSwapavoid shifting elements when order does not matter. -
FNamecomparison is an integer compare, but creating anFNamefrom a string hashes the string and consults the name table. Cache names that you use every frame in astatic const FName, asApplyCoverColordoes with the cover colour parameter. -
FStringallocates; building strings every frame creates garbage. Log withVerbosefor per-frame traces so that they cost nothing unless enabled. -
Dynamic delegates are slower than native ones (name lookup, reflection). Use them where Blueprint must listen, and native multicast delegates for C++-only events.
-
Pass
TArray,FStringand delegates by const reference; pass by value only to move into a member withMoveTemp. -
ensureevaluates its expression in every build; keep expensive conditions incheckSlow.
What changed recently
| Version | Change |
|---|---|
UE 5.0 (2022) |
|
UE 5.2 (2023) |
|
UE 5.8 (2026) |
The documentation for the coding standard, containers, delegates, logging and asserts used here is unchanged in substance; the Epic standard asks for explicit lambda captures and weak delegate bindings, as shown above. |
See also
-
UObject, Reflection and Garbage Collection:
UPROPERTY,TObjectPtr, weak and soft pointers. -
C++ and Blueprints Together: exposing these types to Blueprint.
-
Blueprint Communication: dispatchers are dynamic multicast delegates.
-
Project Structure and Modules: where
Bookshelf.hand the module macro live. -
Profiling and Optimization: measuring the cost of the idioms above.
-
C++ containers: the standard-library counterparts of
TArray,TMapandTSet. -
C++ strings and text:
std::stringversusFString,FNameandFText. -
C++ functions and lambdas: capture rules behind the lambda guidance.
-
C++ memory management and smart pointers:
std::shared_ptrversusTSharedPtr. -
C# delegates, lambdas and events: the same observer idea in C#.
-
Unity: Project Architecture and Design Patterns: event patterns in Unity.