In c++, where should constant strings be placed?
In Java, you can write an Interface, where you put all the constant strings
What about ue c++?
In c++, where should constant strings be placed?
In Java, you can write an Interface, where you put all the constant strings
What about ue c++?
For what purpose? You can define static const strings or FNames in cpp files (doesn’t have to be part of a class or interface). If you’re thinking about localization, this page might be helpful Text Localization | Unreal Engine Documentation
In fact, it is for unified management
Such as:
a.cpp
void Test(TMap<FString, UObject*> Map){
UObject* obj = Map["Name"]
}
b.cpp
void Test(TMap<FString, UObject*> Map){
UObject* obj = Map["Name"]
}
The same Map is used in different files, I want key to be a constant string, Easy to maintain
Sure that’s fine. In a header which you include in multiple cpp files:
// Declare the constant string:
extern const FString SomeString;
In a single cpp file:
#include "SomeString.h"
// Define the constant string:
const FString SomeString = "Something";
In any cpp file:
#include "SomeString.h"
// Use the constant string:
void Test(const TMap<FString, UObject*>& Map){
UObject* obj = Map[SomeString];
}
Some other tips:
TMap
(and other containers like TArray
) by reference, like const TMap<...> & Param
or TMap<...> & Param
if you want to modify it. Otherwise you’re copying the container every time you pass it as an argument to a function.FName
rather than FString
for these. It’s much faster to compare names than strings and they’re a natural fit for TMap
keys for this reason.Possibly better to use #define for these as well, rather than allocating additional memory for the consts.
thank you ~~~