TArray Pass by Reference?

Hi~

I am trying to use the function UGameplayStatictics::GetAllActorsOfClass(UObject WorldContextObject,TSubclassOf< AActor > ActorClass, TArray< AActor > & OutActors).

I have problems with the OutActors part.

I have this in my .h class:
TArray Engines;

And I try to pass this TArray to the GetAllActorsOfClass function like:
UGameplayStatics::GetAllActorsOfClass(this, AEngine::StaticClass(), Engines);
But VS keeps telling me that "a reference of type “TArray &” (not const-qualified) cannot be initialized with a value of type “TArray”.

I have been struggling with this error all night…I know it must be simple fix but cannot figure out how.

I’d really appreciate it if anyone can tell me how to fix this error. Thanks!

Example:

TArray<AActor*> OutActors;

UGameplayStatics::GetAllActorsOfClass(World, ADestructibleActor::StaticClass(), OutActors);

Hi ,

I’ll give an explanation of Pierdek’s answer. The issue here is your initialization of ‘Engines’ array. Any container in Unreal C++ that begins with a ‘T’ is known as a template e.g. in this case a Template Array. You need to define what contents will be stored in your TArray by giving it an object class type

TArray<ObjectClass*> ArrayName;

// example given by Pierdek is a TArray which holds AActor objects
TArray<AActor*> OutActors;
1 Like

Hi,

It sounds like you are trying to pass a const array, which probably means you are trying to call GetAllActorsOfClass from a const member function.

C++ has qualifier transitivity over subobjects, meaning if your class is const, then your ‘Engines’ member will be const too:

// This is a const function, so UMyClass is const here...
void UMyClass::DoSomething() const
{
    // ... and so Engines will be const here too, and so it won't compile
    UGameplayStatics::GetAllActorsOfClass(this, AEngine::StaticClass(), Engines);
}

You can’t pass a const array to GetAllActorsOfClass, because GetAllActorsOfClass needs to modify it in order to fill it up with actor pointers.

DoSomething probably needs to be non-const, because it’s changing the state of your UMyClass (by modifying the Engines subobject), Or if your Engines subobject isn’t part of the ‘visible state’ of UMyClass then perhaps you need to make Engines mutable, but I’d be careful with that. Read here:

What do I do if I want a const member function to make an "invisible" change to a data member?, C++ FAQ.

Steve