How to return an array reference in C++

Hi,

I would like to have a const getter method to access a private array in my class. By removing the const keyword the problem is gone.
Is it possible? Does it make sense?

I also notice that if I use the GetStarClusters() in a blueprint the performance is way way worse than accessing the property directly. Is it normal? It seems it’s creating copies from the array when I call the method.

NOTE: FStarCluster is a BlueprintType struct .

public: 
	UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Stars System")
	FORCEINLINE TArray<FStarCluster>& GetStarClusters() const { return StarClusters; }

private: 
	UPROPERTY(BlueprintReadOnly, Category = "Stars System")
	TArray<FStarCluster> StarClusters;

Thanks in advance!
Mateus.

See this (first answer)


Blueprint VM tends to do lots of copying around arguments regardless of whether you specify them as ref or not. You can take a look at ProcessEvent and the UHT generated code (files in .generated.h and .gen.cpp) to understand the way it works. Accessing the property directly is faster.

1 Like

Thanks for the quick reply!

If I understood correctly, the suggestion is to add const to the return type, right?

	UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Stars System")
	FORCEINLINE **const** TArray<FStarCluster>& GetStarClusters() const { return StarClusters; }

this is causing this compilation error:

Inappropriate keyword 'const' on variable of type 'TArray'

This error makes no sense to me as I can use const for parameters of type TArray. I understand the contexts are different, but why?
I’m wondering if I’m doing something wrong but I’m blind.

That one is not a C++ error but is thrown by UHT.

It just tells you that it makes no sense to return a const ref here because blueprints will be able to manipulate it anyways, since it doesn’t support const-ness in C++ terms.

Using const& in a function argument is different. By default for reference arguments the BP system produces an output pin. const& tells the BP to produce an input pin, while still benefiting from optimization (no copies) on C++ side. It does still generate copies for the BP side though…

1 Like

Now everything makes sense :smiley:

Thanks for the explanation, really appreciate that!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.