Based on the author’s years of industry experience and combined with best practices for Unreal Engine projects, the following coding standards have been compiled.
This article strives to be well-reasoned and may be revised periodically in the future.
Last revised: 2026-01-06
Unless there are special circumstances, the following coding standards should be followed to prevent unexpected issues.
This article will list as many situations encountered in programming as possible, along with the problems solved by adopting these coding standards. The goal is to enable different programmers to arrive at a single coding format when facing the same requirement. If a certain behavior is not explicitly mentioned in this text, it can be regarded as undefined behavior, and you may judge whether it conforms to the standards based on your own practice.
This article may use the following tags to indicate the strictness of enforcement: 说明提议推荐强制
For native C++, refer to: C++ Project Coding Standards
Programming Approach
推荐If the framework provides the same interface, prefer the framework-provided interface unless strict consistency is required.
推荐For cases where the foreseeable time complexity is less than O(n) (n<100), code maintainability is often more important than runtime efficiency.
Code References
Copyright Notice
提议If a file may be used by multiple projects, it is best to add a copyright notice at the top of each file, for example:
| |
Header Files
- 强制There is no need to use macros to prevent duplicate inclusion; instead, use
#pragma once, which is supported by most compilers currently in use. - 建议When including, try to directly include the smallest unit header file needed.
- For example, do not include
Core.h; instead, include the specific header files needed for definitions in the core. - This avoids introducing unnecessary dependencies when including header files, which increases compilation time and hinders header file organization.
- For example, do not include
- 建议Inserting blank lines in
#includeto separate related header files, C libraries, C++ libraries, other libraries’.hfiles, and this project’s.hfiles is a good habit. - 强制Avoid directly referencing a certain class in header files as much as possible; instead, include other header files in the cpp.
- Consider prioritizing forward declarations to use another class in a header file, and then actually include it in the cpp. This effectively organizes the structure and avoids circular references.
- 建议As much as possible, include files in the following order: the cpp’s corresponding header file, C++ standard library files, framework header files, third-party header files, project common header files, and specific feature header files, to facilitate understanding of the file reference structure.
- 强制When including header files, avoid using relative positions as much as possible, such as ....\NetDef.h, as this hinders file organization and understanding of the file structure.
- 强制Avoid using backslashes
\to mark paths, as some compilers may have issues; use forward slashes/to mark paths.
Forward Declaration
A “forward declaration” is a pure declaration of a class, function, or template without its definition.
说明Forward declarations can save unnecessary recompilation time. Redundant #include forces the compiler to expand more files and process more input, causing code to be recompiled multiple times due to unrelated changes in header files.
Inline Functions
An inline function is a special kind of function whose body is expanded directly at the call site, rather than jumping to the function body for execution like a normal function.
- 说明Reasonable use of inline functions can improve code execution efficiency.
- 提议Only define a function as inline when it has 10 lines or fewer.
- 强制Be cautious with destructors; destructors are often longer than they appear because implicit members and base class destructors are called.
- 建议Inlining functions containing loops and switch statements is usually not worth it.
- 说明Declaring a function as inline does not guarantee the compiler will inline it; virtual functions and recursive functions will not be inlined normally.
- 建议Functions defined inside a class are generally automatically inlined. Therefore, once a function no longer needs to be inlined, its definition should no longer be placed in the header file but in the corresponding cpp file. This keeps the class in the header file quite concise and well implements the principle of separating declaration from definition.
Example
| |
Scope
Namespaces
- 说明Namespaces subdivide the global scope into independent, named scopes, effectively preventing naming conflicts in the global scope.
- 强制Prohibit using
using namespace xxx; - 强制Prohibit using inline namespacesC++
1 2 3 4 5namespace X { inline namespace Y { void foo(); } }- X::Y::foo and X::foo are equivalent.
- Inline namespaces are mainly used to maintain ABI compatibility across versions. (Generally not needed.)
- Using anonymous namespaces in header files violates C++’s One Definition Rule (ODR).
Anonymous Namespaces and Static Variables
- 提议When defining a variable in a .cpp file that does not need to be referenced externally, place it in an anonymous namespace or declare it as
static.- 说明This name is only visible in the current
.cppfile; other.cppfiles cannot access it at all.- This means that the identifiers you declare in this file cannot be accessed in another file.
- Even if two files declare identifiers with exactly the same name, the entities they point to are actually completely different.
- 强制Do not use in header files.
- 说明This name is only visible in the current
| |
Local Variables
强制Place function variables in the smallest possible scope and initialize them at the point of declaration.
- The closer to first use, the better, making it easier for readers to locate variable declarations.
- Explicitly initializing local variables at declaration is more efficient than the two-step process of implicit initialization followed by assignment, and also implements the important computer architecture concept of “locality.”
- Objects: Declaring outside the loop scope is much more efficient.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22int i; i = f(); // Bad — initialization and declaration separated int j = g(); // Good — declared at initialization vector<int> v; v.push_back(1); // Better to use brace initialization v.push_back(2); vector<int> v = {1, 2}; // Good — v is initialized from the start // Inefficient implementation for (int i = 0; i < 1000000; ++i) { Foo f; // Constructor and destructor called 1000000 times! f.DoSomething(i); } Foo f; // Constructor and destructor called only once for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); }- Variables belonging to
if,while, andforstatements should be properly declared within these statements, so that their scope is limited to these statements, for example:
C++1while (const char* p = strchr(str, '/')) str = p + 1;
Static and Global Variables
- 说明Native data types POD (Plain Old Data)
- Basic types such as int, char, float; pointers, arrays, and structs of POD types.
- 说明Static storage duration variables
- Global variables, static variables, static class member variables, and function static variables.
- 说明Within the same translation unit (cpp), the behavior is well-defined: static initialization takes precedence over dynamic initialization, initialization order follows declaration order, and destruction is in reverse order. Between different translation units, the order of initialization and destruction is undefined behavior.
- 强制Do not use function return values to initialize POD variables unless the function does not involve any global variables (such as
getenv()orgetpid()).- Exceptions are static variables within a function’s scope, since their initialization order is well-defined and only occurs when execution reaches their declaration.
- 强制Use
quick_exitinstead ofexit; the former does not execute any destructors or any handlers bound viaatexit. - 建议Prohibit using static storage duration variables of class types, because in this case the order of constructor and destructor calls is indeterminate, leading to hard-to-find bugs. (Object A depends on object B, but object B is destroyed before A.)
- If you really need a static or global variable of class type, you can use the singleton pattern.
Classes
Constructors
- 强制Avoid complex initialization logic in constructors as much as possible to ensure the object is correctly constructed.
- 强制Do not call the class’s own virtual functions in constructors; such calls will not be redirected to the subclass’s virtual function implementation, and even if not currently overridden by a subclass, it is a future hazard.
- Virtual functions in C++ allow dynamic binding at runtime, i.e., determining which virtual function implementation to call based on the actual object type at runtime. This dynamic binding is implemented through the virtual function table (vtable). When a virtual function is called in a constructor, since the object is not yet fully constructed, the vtable pointer may not have been properly initialized, resulting in the inability to correctly call the virtual function implementation.
- When a virtual function is called in a constructor, if the base class constructor calls a virtual function, due to the dynamic binding mechanism, it may call a function in the derived class that has not been fully constructed. This may lead to incorrect object state or even undefined behavior.
Implicit Type Conversions
- 建议Do not define implicit type conversions. For conversion operators and single-argument constructors, use the
explicitkeyword.- Implicit type conversions hide type mismatch errors. Sometimes the target type does not match the user’s expectation, or the user is not even aware that a conversion occurred.
- Implicit type conversions make code harder to read, especially when there are function overloads, as it becomes difficult to determine which function is being called.
Copyable and Movable Types
- 建议If you need to explicitly define copy and move operations, otherwise disable the implicitly generated copy and move functions.
- If needed, make your type copyable/movable. As a rule of thumb, if the copy operation is not immediately obvious to your users, do not make the type copyable. If you make a type copyable, be sure to define both the copy constructor and the assignment operator, and vice versa. If you make a type movable and the move operations are more efficient than copy operations, then also define both move operations (move constructor and move assignment operator). If the type is not copyable but the correctness of move operations is obviously visible to users, then make the type move-only and define both move operations.
- 强制If copy/move operations are defined, ensure that the default implementations of these operations are correct. Always check the correctness of default operations and document whether the class is copyable and/or movable.
| |
- 建议If your class does not need copy/move operations, explicitly disable them by using
= deletein thepublicsection or other means.
| |
Inheritance
- 强制If a class has an inheritance relationship, the destructor needs to be virtual.
| |
Multiple Inheritance
建议At most one base class is a non-abstract class; all other base classes are pure interface classes.
建议If diamond inheritance occurs, it usually means there is a design problem.
Operator Overloading
- 提议Operator overloading can be confusing, making people mistakenly think that time-consuming operations are as lightweight as operations on built-in types. Use with caution.
Member Variables
强制Generally, it is not recommended to mark member variables as public, as it is easier to miss changes when the interface changes. Moreover, for a public variable, the object itself has less control over it, which is not conducive to constraining its read/write behavior. Consider adding public Set and Get interfaces to operate on it.
For example:
| |
If the caller mistakenly uses FString& SaveKey = StarsSaveGame->OverrideSaveKey, the member variable will be incorrectly modified.
If changed to a function return, there is no such hazard, and a warning will be obtained at compile time:
Binding r-value to l-value reference is non-standard Microsoft C++ extension
| |
Structs
Member Variable Initialization
强制Pointers used in code must be initialized. When creating structs on the stack, pointers are not initialized by UE, resulting in wild pointers.
As follows:
| |
However, not all member variables need to be initialized. For example, container classes like TArray and TMap are initialized in their constructors. For some structs, initializing directly through assignment may actually cause problems. Refer to: A rather tricky compilation error with TWeakObjectPtr. In such cases, if initialization is needed, it can be done in the constructor to avoid unexpected behavior.
Enums
- 强制If enum values need to be exposed to Blueprint, they must be within the
uint8range; otherwise, unexpected issues may occur in some cases.- If it is only for Reflection, this rule may be disregarded.
- 提议If you want large-value enums but do not want to hardcode values in Blueprint, consider using
FNameto correspond to them, preferably maintained via a table.
Enum Value Type
强制Enum values should be defined using enum class with the underlying storage type specified, rather than directly using enum.
enum cannot specify the underlying data type. The storage structure of the same enum may differ across compilers, which can sometimes reduce code portability. After changing to enum class, the specific storage structure can be specified, giving developers more control over its structure.
enum has implicit conversion to integers. Although implicit conversion is sometimes convenient for developers, it does not produce clear errors when incorrectly assigned or encoded, so implicit conversion is not recommended. After changing to enum class, if conversion is needed, static_cast can be used for explicit conversion.
enum cannot define duplicate names. To solve this problem, enum generally requires adding the type name to the enum value names, which can make enum values lengthy in some contexts. enum class does not have this problem, and enum values can be named according to the design.
Enum Value Naming
强制Enum types should be named starting with E, such as EUnitClientType. This rule should be followed even if not exposed to Blueprint.
Because enum values are often directly used for comparison, following this convention helps distinguish enum values from ordinary types and makes it easier for code completion tools to find specific enums.
Enum Value Order
Unless it is clearly known that changing the order will not cause any impact, do not modify the order of enum values, as it may cause logic or data incompatibility.
If the order of enum values should not be modified (generally because they are referenced in configuration tables or other logic), consider explicitly writing out their values with =.
If enum values have no fixed values, it can be assumed by default that changing the enum value order does not affect logic.
Enum Value Example
| |
Exceptions
The “exceptions” mentioned here do not refer to thrown exceptions (
throw), but rather error situations that may occur in code.
建议Pay attention to error handling. For functions that may fail, consider adding a bool return value to indicate whether the operation was handled normally.
建议If there may be multiple types of errors, it is recommended to return error codes to identify the error type.
Error Codes
建议Consider using an EErrorId enum to represent error codes.
强制Avoid hardcoding int32 error values in logic. Use error codes in C++, and use FName in Blueprint or Lua.
建议You can use functions in UErrorIdLibrary to convert between enum/int32/FName.
建议To check whether an int32 is OK, use UErrorLibrary::IsErrorIdOK.
强制To check whether an int32 matches a specific enum, convert the enum to int32 for comparison.
强制Avoid converting int32 to enum for comparison, as it may not be a valid enum and may produce unexpected results.
Functions
Inputs and Outputs
建议For performance and safety reasons, return values by reference as much as possible. If concerned about member variables being modified, use
const.建议Place input parameters before all output parameters.
建议For cases where output is obtained through passed-in reference parameters, be careful to initialize the passed-in parameters when necessary, to prevent the function from terminating early and causing output inconsistent with expectations.
| |
Writing Short Functions
建议If a function is particularly long, consider splitting it without affecting the program structure.
说明One aspect of compiler optimization is eliminating common subexpressions. The larger the function, the more work the compiler has to do to identify them, which greatly increases compilation time.
Const Correctness
- 建议Do not pass by value directly; avoid a memory copy by passing const reference parameters.
| |
- 建议If a method does not modify the object, mark it as a const function.
- Const member functions promise not to modify the class’s member variables, improving code safety and preventing accidental data modification and potential errors.
- Code logic is clearer; it is immediately obvious that this is a read-only function.
- Gives the compiler room for optimization.
- Avoids the situation where callers cannot mark their own functions as const.
| |
- If a loop does not modify the container, use const iteration over the container.
| |
Function Overloading
- If function overloading is used, the reader must be able to understand the call at a glance without having to guess which overloaded function is being called. This rule also applies to constructors.
| |
- If a function is overloaded solely by different parameter types (meaning the number of parameters is unchanged), the reader must be very familiar with C++’s various matching rules to understand exactly how the matching process works. Additionally, if a derived class only overrides some variants of a function, the inheritance semantics can easily become confusing.
Default Parameters
- 说明Default parameters are actually another way of implementing function overloading semantics.
- 强制Default parameters are not allowed for virtual functions inherited by subclasses.
- Virtual functions are dynamically bound, while default parameter values are statically bound. That is, virtual functions determine the type at runtime, while default parameter values are determined at compile time.
- If redefined, the program will use the base class virtual function’s default parameters, which is obviously not the desired result.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66#include <stdlib.h> #include <stdio.h> #include <iostream> class Shape { public: enum Color { Red, Green, Blue, }; virtual void draw(Color color = Red) = 0; static std::string ColorToString(Color c) { switch (c) { case Red: return "Red"; case Green: return "Green"; case Blue: return "Blue"; default: return ""; } } }; class Rectangle : public Shape { public: virtual void draw(Color color = Green) override { std::cout << "Rectangle : " << ColorToString(color) << std::endl; } }; class Circle : public Shape { public: virtual void draw(Color color) override { std::cout << "Circle : " << ColorToString(color) << std::endl; } }; int main() { Rectangle R; Circle C; R.draw(); // Output: Rectangle : Green //C.draw(); // Error, static binding cannot inherit default parameters Shape* pr = &R; Shape* pc = &C; pr->draw(Shape::Blue); // Output: Rectangle : Blue pc->draw(Shape::Blue); // Output: Circle : Blue // Static binding, uses base class default parameters, performs derived class action pr->draw(); // Output: Rectangle : Red pc->draw(); // Output: Circle : Red return 0; }
Lambda Expressions
- 强制Do not use default captures (=, &); explicitly write out all variable captures.
- This mainly targets asynchronously executed Lambda expressions, where captured variables may have become invalid by the time of execution.
- Synchronous lambda expressions generally have no side effects, so they can be used, for example: Foreach and similar.
- 强制Asynchronous callback Lambda expressions should capture local variables.
- 强制Lambdas should not capture raw UObject pointers.
- If the captured raw UObject pointer has been GC’d and a new UObject has been allocated at the same memory location before the asynchronous callback executes.
- If the expired UObject is written to in the callback at this point, it amounts to writing to unknown memory, potentially corrupting the new UObject.
- You can use TWeakObjectPtr to check validity at execution time.
| |
Configuration
- 强制Consider the need for hot-update configuration; be cautious about caching configuration and prefer looking up tables by
RowName.
Callbacks
- 推荐Use callbacks with caution, especially paying attention to whether there is cross-frame logic or recursive logic.
- 推荐Be cautious about caching Delegates, as this may cause closure anomalies.
- For example, if a Delegate is modified within its own callback, the captured variables will be in an abnormal state.
Standard Library
推荐UE has its own template library, and in most cases the UE-provided version should be used.
However, there are some exceptions; refer to the official documentation: Use of the Standard Library
Layout and Formatting
Naming Conventions
- 强制Each word in a name (such as a type or variable) should have its first letter capitalized, with no underscores between words. For example:
HealthandUPrimitiveComponent, notlastMouseCoordinatesordelta_coordinates. - 强制Type names require an additional uppercase letter prefix to distinguish them from variable names. For example:
FSkinis a type name, whileSkinis an instance ofFSkin. - 强制Template classes are prefixed with T.
- 强制Classes inheriting from
UObjectare prefixed with U. - 强制Classes inheriting from
AActorare prefixed with A. - 强制Classes inheriting from
SWidgetare prefixed with S. - 强制Interfaces are prefixed with I.
- 强制Enums are prefixed with E.
- 强制Boolean variables must be prefixed with b (e.g.,
bPendingDestructionorbHasFadedIn). - 强制Most other classes are prefixed with F, while some subsystems use other letter prefixes.
- 强制Typedefs should be prefixed with any letter appropriate to their type: F for struct typedefs, U for
UObjecttypedefs, and so on.- 推荐Typedefs of specific template instantiations are no longer templates and should be prefixed accordingly, for example:
C++1typedef TArray<FMytype> FArrayOfMyTypes; - 推荐Even if not exposed to Blueprint, this naming convention can be followed to align with UE standards.
- 强制Types and variables are named as nouns.
- 强制Method names are verbs, describing the method’s effect or the return value unaffected by the method.
- 强制All functions returning bool should ask a true/false question, such as
IsVisible()orShouldClearBuffer(). - 推荐If a function parameter is passed by reference and the value will be written to the function, it is recommended to prefix the parameter name with “Out” (optional). This clearly indicates that the value passed in will be replaced by the function.
- 推荐If the In or Out parameter is also a boolean, prefix In/Out with b, such as
bOutResult. - 强制Functions that return a value should describe the returned value. The name should indicate what the function will return. This rule is extremely important for boolean functions. Refer to the following two example methods:
- 强制RPC functions should have Server, Client, or Multicast placed before the function name.
| |
- 推荐For abbreviated words, it is recommended to still use the format of capitalizing the first letter and lowercasing the rest.
- This avoids getting into disputes about what is an abbreviation and what is not.
- PHP->Php
- For complex variable names, this provides clearer display.
- Such as HTTPSubsystem->HttpSubsystem
- UE internal variables use both forms, mainly capitalizing only the first letter.
- This avoids getting into disputes about what is an abbreviation and what is not.
Naming examples:
| |
Code Formatting
推荐No more than 120 characters per line.
强制Avoid non-ASCII encoding as much as possible; file encoding must be UTF-8.
推荐Use tab character \t for indentation.
推荐Brace formatting must be consistent. In Epic’s traditional practice, braces are always placed on a new line. Please follow this format.
强制Always use braces in single-statement blocks. For example:
| |
- 强制All execution blocks in if-else statements should use braces.
- This is to prevent errors during editing — without braces, another line may accidentally be added to the if block. The extra line is not controlled by the if expression, resulting in poor code.
- Conditionally compiled items that interrupt if/else statements can also cause bad results. Therefore, always use braces.
| |
switch statements
- switch needs a default branch; if no logic needs to be executed, write break.
- Logic exceeding one line needs braces, with break placed outside the braces.
- If there is only a single-line return logic, the break statement can be omitted.
- In other cases, the logic should be placed inside braces, with break outside the braces.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21switch (condition) { case 1: ... // fall through case 2: ... break; case 3: ... return; case 4: case 5: ... break; default: break; }
Comments
Standards
- 推荐Describe more about How to use and Why it is written this way; there is no need to describe What it is, as the code implementation already clearly describes (or should strive to clearly implement) what it is.
- 推荐It does not matter whether it is in English or not; code is read by people within the project team, so as long as everyone can understand it.
- Function comments
- Doxygen comment format is recommended; UE can correctly recognize common tags.
- General function description
- Description of each parameter
- Description of return value
| |
Principles
- 强制Write code with clear meaning:
| |
- 推荐Write useful comments:
| |
- 推荐Do not comment low-quality code — rewrite it:
| |
- 强制Do not let code contradict comments:
| |
TODO
推荐Use TODO comments for temporary, short-term solutions, or code that is good enough but not perfect.
推荐Mark places that are unfinished or not satisfactorily completed, so that a search will reveal what work remains to be done, saving even the effort of keeping a log.
| |
Other Related Topics
Sizeof
推荐Use sizeof(varname) instead of sizeof(type) as much as possible.
推荐If the type of varname changes, sizeof(type) will most likely be forgotten and cause a bug.
Iterators
提议Pre-increment is more efficient, saving a copy, but most compilers can optimize it correctly.
强制Be alert to iterator invalidation, generally when adding or removing elements from a container within a loop.
- TArray
- Memory reallocation caused by adding elements
- Removing elements
- Inserting elements
- TArray
Infinite Loops
- 强制Infinite loops caused by incorrect use of unsigned integers.
| |
- 说明The return type of a container’s size() is size_t, which is an unsigned integer.
| |
- 强制Be alert to while loops where the condition is never satisfied.
Floating-Point Numbers
- 强制When checking whether floating-point numbers are equal, do not use == directly, as floating-point precision issues will cause incorrect judgments.
| |
std::vector<bool>
- 强制Try not to store bool types in vector; for optimization purposes, vector does not actually store bool internally.
- Of course, for UE, TArray should be the preferred choice in most cases.
Null Pointers
- 强制Use nullptr instead of NULL for null pointers as much as possible.C++
1 2 3 4 5 6 7 8 9 10 11void func(char*) { cout << "char*"; } void func(int) { cout << "int"; } int main() { func(NULL); // Compilation fails: error: call of overloaded 'func(NULL)' is ambiguous func(nullptr); // char* return 0; }
Numeric Overflow
- 强制When using FMath::RandRange, be aware of numeric overflow.
| |
Memory
Common Issues
推荐Avoid using native arrays; use UE containers as much as possible.
- Native arrays cannot check for out-of-bounds access.
强制Null pointers not checked.
- Null pointer crashes account for the majority.
- Defensive programming.
强制Be alert to buffer overflows.
- Use memory operation functions such as sprintf, printf, memcpy, memset, strcat, strcpy, etc. with caution.
- The above functions do not check for out-of-bounds when copying memory. If an overflow occurs, it will corrupt other unrelated memory, causing unpredictable bugs.
C++1 2 3 4 5 6void foo() { char szName[10]; int n = 0; strcpy(szName, "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf"); }强制Prohibit returning local references; the memory will be destroyed.
C++1 2 3 4 5int* foo() { int xxx = 0; return &xxx; }强制Prevent uninitialized pointers.
- UObject members with UPROPERTY are automatically initialized to nullptr.
- Ordinary pointers that are not initialized point to arbitrary addresses.
- The if check is already invalid; writing data to a wild pointer.
- Note: Pointer members of USTRUCT are not initialized to nullptr even with UPROPERTY; they need to be manually initialized.
强制Incorrect type casting.
- Prefer using UE-provided Cast for UObject type conversion.
- Secondarily use C++ type casts, avoiding C-style casts.
- static_cast, do not use C-style casts.
- const_cast, removes const qualifier.
- reinterpret_cast, unsafe conversion between pointer types and integers or other pointers.
- When a program performs incorrect type casting, unpredictable results occur. This may cause the program to crash, corrupt memory, or produce incorrect output.
C++1 2 3 4 5 6 7int main() { int num = 10; double *ptr = (double*)# // Incorrect type cast *ptr = 5.0; // Out-of-bounds write std::cout << *ptr << std::endl; return 0; }强制Memcpy, memset used on non-POD types, destroying the vtable pointer.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26class A { public: A() {} virtual void test() { printf("%d", nn); } protected: int nn; }; class B : public A { public: B() {} virtual void test() override { A::test(); printf("B::test, %d", nn); } }; B b; memset(&b, 0, sizeof(b));强制Self-destruction within a function, causing subsequent code accessing or writing member variables to corrupt memory.
- Certain states will stop the Behavior Tree, and this function executes directly in a Behavior Tree Task node (stopping the Behavior Tree within the Task).
- The Behavior Tree Task node attempts to delete the Behavior Tree Owner’s Actor (dangerous operation; should be deferred by one frame).
- Be careful with self-destruction operations; consider whether deferring by one frame is needed.
强制Loop operations not taking references, causing struct copies.
强制Lambda expression self-destruction, causing memory issues from using captured variables after they are destroyed.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14TWeakObjectPtr<UWorldManager> thisObject(this); Stars::Message::PvpTrigger triggerData = trigger; GetWorld()->GetTimerManager().SetTimer(PvPingTimerHandle, FTimerDelegate::CreateWeakLambda(this, [thisObject, triggerData](){ if (!thisObject.IsValid()) return; // Do something // The Lambda expression is destroyed here, causing thisObject to be destroyed thisObject->GetWorld()->GetTimerManager().ClearTimer(thisObject->PvPingTimerHandle); // Using thisObject here is already unsafe } }), 1, true);
Smart Pointers
- 强制Prefer using Smart Pointers when managing objects that need to be manually
newed.- A raw pointer wrapped by multiple smart pointers.
- After the first smart pointer is destroyed, the memory is destroyed; subsequent writes corrupt memory.
C++1 2 3 4 5int* rawPtr = new int(5); TSharedPtr<int> p1 = MakeShareable(rawPtr); TSharedPtr<int> p2 = MakeShareable(rawPtr); p1 = nullptr; *p2 = 7;- TSharedPtr
- Reference Counting
- TUniquePtr
- Can only transfer ownership
- Beware of circular references
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30class B; class A { public: ~A() { std::cout << "~A" << std::endl; } TSharedPtr<B> b; }; class B { public: ~B() { std::cout << "~B" << std::endl; } TSharedPtr<A> a; }; int main() { TSharedPtr<A> a = MakeShared<A>(); TSharedPtr<B> b = MakeShared<B>(); a->b = b; b->a = a; a = nullptr; b = nullptr; return 0; }- TWeakPtr
- Resolves circular references
- A raw pointer wrapped by multiple smart pointers.
Containers
强制Be alert to deletion and addition within loops.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24void erase(std::vector<int> &vec, int a) { for (auto iter = vec.begin(); iter != vec.end();) { // This is correct if (*iter == a) { iter = vec.erase(iter); } else { ++iter; } } for (auto iter = vec.begin(); iter != vec.end(); ++iter) { // error if (*iter == a) { vec.erase(iter); // error } } }- Copy to a new container before performing loop deletion.
- Use iterators.
强制Be aware of memory reallocation issues.
- TArray
- TMap also has this issue.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20struct TestStruct { int a = 0; bool b = false; float c = 0.0f; FString s; ~TestStruct() { UE_LOG(LogTemp, Log, TEXT("~TestStruct")); } }; TMap<int, TestStruct> structMap; TestStruct* val1 = &structMap.Emplace(1); TestStruct* val2 = &structMap.Emplace(2); for (int i=0;i<10000;i++) { structMap.Emplace(i); }
UE Memory Management
GC Mechanism
UE uses the mark-and-sweep algorithm for GC. When an object’s reference chain is unreachable, GC reclaims the memory occupied by that object. Before GC, UE starts from the root set and marks all UObject objects, marking active objects and clearing all unmarked inactive objects.
GC is typically triggered at specific times, such as Level transitions, game loop cycles, etc., to avoid excessive impact on game performance.
强制Developers need to properly manage object references in UE, avoiding unnecessary long-term references, to ensure that GC can correctly reclaim unused memory resources, thereby improving game performance and stability.
Weak Pointers
- 强制Use UObject weak pointers to determine whether an object is still within its lifecycle.
- Points to a specific UObject via its index in GUObjectArray.
- Self-incrementing serial number verifies the validity of the pointer.
| |
强制Be alert to issues with using UObject or its weak pointers on non-main threads.
- UObjects are GC’d on the main thread, so their lifecycle cannot be predicted on non-main threads.
- Therefore, try not to access UObjects or their weak pointers on non-main threads. Back up all data that non-main threads need to process on the external main thread, pass it in via Lambda expressions, and access UObject weak pointers only after returning to the main thread.
C++1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43TWeakObjectPtr<UBuildingSearchProxy> WeakThis(this); uint8 Id = WeakThis->Id; FString SearchInput = WeakThis->SearchInput; TArray<FName> List = WeakThis->List; AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [WeakThis, Id, SearchInput, List] { if (!WeakThis.IsValid()) return; TSet<FName> SearchResult; for (const FName& Part : List) { if (Id != IdCounter) break; #if WITH_EDITOR if (Part.ToString().Contains(SearchInput)) { SearchResult.Add(Part); continue; } #endif const FItemTableRow* pRow = UDataManager::FindRow<FItemTableRow>(Part); if (pRow != nullptr && pRow->DisplayName.ToString().Contains(SearchInput)) { SearchResult.Add(Part); } } AsyncTask(ENamedThreads::GameThread, [WeakThis, SearchResult] { if (!WeakThis.IsValid()) return; if (WeakThis->Id == IdCounter) { WeakThis->PostSearchResult.Broadcast(SearchResult); } WeakThis->SetReadyToDestroy(); }); });推荐Avoid storing raw pointers to UE interfaces as member variables.
- To determine lifecycle, store a UObject weak pointer TWeakObjectPtr and Cast it to an interface pointer when using it.
- In terms of approach, if you need to indicate a reference relationship yourself, use UPROPERTY with TObjectPtr; otherwise use TWeakObjectPtr.
C++1 2 3 4 5TWeakObjectPtr<UObject> CauserAttributePtr; // Damage causer TWeakObjectPtr<UObject> TakerAttributePtr; // Damage taker IAttributeInterface* GetCauserAttributeInterface() const; IAttributeInterface* GetTakerAttributeInterface() const;
Networking
Proto
强制Prohibit directly caching the Proto structure of messages; the memory may be reallocated or reclaimed.
强制If you need to save, call the project-encapsulated interface, or use the CopyFrom interface on Proto.
强制Consider using FByteArray or FByteCompressedArray to conveniently save generic data.
Logging
Logging Standards
- 强制Important events in each functional module should be logged as much as possible (as long as they do not occur frequently and repeatedly).
- 推荐Do not output useless information or overly frequent prints (can be controlled via Verbosity level).
- 推荐For newly added modules, log enough to reconstruct the scene as much as possible.
- 强制Behaviors involving player values, such as item gain/loss, experience gain, currency circulation, equipment upgrades, etc., should be logged as much as possible.
- 强制If the volume is too large, consider merging before printing.
- 强制Avoid using trigraphs.
- In C and C++, a trigraph is a special character sequence that starts with two question marks (??) and ends with another character. For example, “??=” represents #, “??/” represents , etc. These trigraphs were designed to handle situations in early encoding systems where certain characters were not available, but in modern encoding systems, these trigraphs are no longer used.
- When the compiler encounters problems converting trigraphs, it will report an error: “trigraph converted to ’ ’ character”. This means the compiler cannot correctly convert the trigraph to the expected character, usually because an error occurred during conversion or an unrecognized trigraph was encountered.
| |
Engine
UObject
- 强制When loading resources in constructors, determine whether it is dynamically created at runtime; CDO generally does not need to load.
- 强制Replicated variables have some rules.
- Cannot be Public.
- Cannot be Blueprint writable.
- To enforce PushModel, writes to replicated variables must be performed within member functions, using the MARK_DIRTY macro.
TMap
- 强制Do not rely on TMap order, especially for data synchronized with the server.
- In many languages, Map implementations are unordered by default.
- 推荐Be cautious when iterating over TMap; pay attention to container size changes during iteration.
- See Containers - Deletion and Addition Within Loops: Client Programming Standards.
- 推荐Be cautious about taking references to TMap values; pay attention to memory reallocation issues.
- See Containers - Memory Reallocation: Client Programming Standards.
- 强制Never use the Map[Key] syntax.
- Use the Find function for lookups instead.
- Relying on Contains interception causes multiple lookups, and the check is not atomic, making it easy to miss.
- UE’s [] internally uses the FindChecked implementation, which attempts to directly retrieve an invalid value when not found.
Blueprint
- 强制Do not create a large array as a local variable in Blueprint; it is very expensive (extract it as a data table).
- 推荐Avoid large functions (a function containing too many Blueprint nodes); instead, split large functions into multiple small functions.
- Use Collapse to turn large functions into small functions.
- Pure functions
- 推荐Declare simple functions as Pure to reduce wiring complexity.
- 强制Avoid using Pure functions to implement complex functional logic; each connection to a Pure node executes it once, affecting performance.
- Conditional checks
- 说明And/Or in Blueprint is not short-circuit evaluation; all pins will execute, which requires special attention.
- For example, placing a validity check and an instance function call on the same And node does not achieve the purpose of intercepting when not valid.
- 说明And/Or in Blueprint is not short-circuit evaluation; all pins will execute, which requires special attention.
- 提示Because Pure functions execute every time, be sure to cache temporary variables when using random nodes and when Pure contains random logic.
Data Tables
- 强制All references in configuration tables must use soft references; this applies to both C++ code and Blueprint structs.
- If hard references are used, loading that resource will force loading of all hard-dependent resources, causing excessively long loading times or hitches during synchronous loading.
- CPP
- Use TSoftClassPtr, TSoftObjectPtr, FSoftObjectPath, etc.
- Blueprint
- Use SoftObjectReference and SoftClassReference.
Replication
- 强制Use PushModel as much as possible.
- Reduces the overhead of comparing whether replicated properties have changed.
- 推荐For complex arrays, the FastArraySerializer mechanism is recommended.
- 说明Map cannot use Replication or RPC in UE.
- 推荐FlushNetDormancy can synchronize in a timely manner, effectively avoiding some network dormancy issues, especially in BaseActor or its Components.
- 说明Unreal does not provide variable replication for CollisionPreset; if there are collision modifications, use Replication or RPC according to the actual situation.
- 说明In Blueprint, resetting variables on the client or server will both trigger RepNotify; the difference is that when the value changes on the server, it will additionally replicate to the client once.
Component
- 强制When iterating over Components, do not call self-destruction, as it will affect the array’s iterator.
Lua
First follow the rules specified by the UnLua implementation, then refer to Lua development habits and standards.
The author recommends abandoning Lua in favor of type-safe programming languages, such as PuerTs.
CheckList
Check whether the following issues exist in the project:
Raw pointer member variables not initialized to null.
Local variables used without initialization.
Array out-of-bounds.
Memory copy buffer overflow.
UObjects requiring strong references not wrapped with UPROPERTY.
UObjects not requiring strong references not using weak pointers.
USTRUCT containing UObject members without UPROPERTY.
Member variables storing raw pointers to UE interfaces.
Calling virtual functions in constructors.
Base class destructors not declared as virtual.
Pointers used without null checks.
Asynchronous callbacks capturing all with & or =.
Asynchronous callback Lambda expressions passing in raw pointers.
Asynchronous callbacks not checking Upvalue lifecycle.
Asynchronous callback Lambda expressions capturing local variables by reference.
Upvalue lifecycle issues caused by Lambda expression self-destruction.
Using exception mechanisms.
Returning references or pointers to local variables.
Manual memory allocation and deallocation not paired.
Incorrect type casting.
Incorrect deletion within container loops.
Smart pointer circular references.
TArray value access without bounds checking.
TArray writes without bounds checking.
TArray previously obtained pointers or references becoming dangling after memory reallocation.
TMap previously obtained pointers or references becoming dangling after memory reallocation.
TMap value access without checking existence first.
Using UObjects on non-main threads.
Using static storage duration variables of class objects.
Diamond inheritance occurring.
Indirect infinite recursive calls causing stack overflow.
Infinite loops.
Key events not logged.
PushModel not used where it should be.
Memset, memcpy used on non-POD structs.
Issues caused by floating-point equality comparison.
UE_LOG parameter type mismatch causing crashes.
Timers set but not cleared, causing Timer leaks.
Division by zero issues.
Loop operations not using references where they should.
Use UE’s built-in typedef basic data types as much as possible (e.g., int32, int64; do not use long, size_t, etc.).
Replicated variables cannot be Public, cannot be Blueprint writable.
All references in configuration tables must use soft references.
References
Google Open Source Project Style Guide
What are some big C++ pitfalls? - Zhihu
Allar/ue5-style-guide: An attempt to make Unreal Engine 4 projects more consistent