参考资料:C++ 模板 | 菜鸟教程
UEC++spawn
在beginPlay里spawn自己是否合理,核心要点不能在beginplay里spawn自己
这个操作会导致栈溢出,接下来可以看一个案例。
这里有一个自定义的类MyActor类,继承自AActor.
#pragma once#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"UCLASS()
class YOURPROJECTNAME_API AMyActor: public AActor
{ GENERATED_BODY()public:// AMyActor();protected:virtual void BeginPlay() override;public:virtual void Tick(float DeltaTime) override;
}
cpp文件
/ MyActor.cpp
#include "MyActor.h"// Sets default values
AMyActor::AMyActor()
{// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;
}// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{Super::BeginPlay();// 错误示范:尝试在自身的BeginPlay里spawn自己// 以下代码会导致死循环和内存爆炸FActorSpawnParameters SpawnParams;GetWorld()->SpawnActor<AMyActor>(AMyActor::StaticClass(), GetActorLocation(), GetActorRotation(), SpawnParams);
}// Called every frame
void AMyActor::Tick(float DeltaTime)
{Super::Tick(DeltaTime);
}
在上述代码中尝试用beginPlay函数尝试spawn自身,这是不合理的操作。因为这个新生成的对象又会spawn自己,如此循环反复。内存占用不断增加,最终程序崩溃。
c++模板的概念
1.基本概念
模板是泛型编程的基础,是一种独立与任何特点类型的方式编写代码。模板是创建泛型类或者蓝图的基础。
库函数里的迭代器和算法都是泛型编程的例子,它们都是属于模板的概念。很多都定义了不同的东西,比如向量,我们可以定义很多不同的向量,比如vector <int>
,可以使用模板来定义类。
2.快速入门
#include <iostream>
#include <string>using namespace std;template <typename T>
inline T const& Max (T const& a, T const& b)
{ return a < b ? b:a;
}
int main ()
{int i = 39;int j = 20;cout << "Max(i, j): " << Max(i, j) << endl; double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; return 0;
}
// 编译执行的结果为
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
这里是每天回答一个问题
如果觉得对你有帮助的话
麻烦点一个赞