我有一个带有Actor类对象的std :: vector
std::vector<Actor> actors(9);
Run Code Online (Sandbox Code Playgroud)
我需要创建一个采用单个输入参数的方法.该方法应该在Vector中找到正确的Actor对象并返回对它的引用.该引用稍后将被被调用者用于更新Object.我试过这样做
Actor& get_actor_ref_from_ped(Ped ped) {
for (int i = 0; i < actors.size(); i++) {
if (actors[i].isActorThisPed(ped)) {
return actors[i];
}
}
/* same issue with this approach
for (auto &actor : actors) {
if (actor.isActorThisPed(ped)) {
return actor;
}
}*/
//return null Actor
return Actor::Actor();
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试从另一个对象更新Actor引用时,它的行为就好像它是按值复制的.这是一个示例代码.actor.hasSpotLight()是1,但vectorActor.hasSpotLight()都是0
void action_next_spot_light() {
Actor actor = get_actor_ref_from_ped(PLAYER::PLAYER_PED_ID());
if (actor.isNullActor() == false) {
if (actor.hasSpotLight()==false) {
actor.setHasSpotLight(true);
log_to_file("actor.hasSpotLight() after " + std::to_string(actor.hasSpotLight()));
for (auto &vectorActor : actors) {
log_to_file("vectorActor.hasSpotLight() after " + std::to_string(vectorActor.hasSpotLight()));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
Actor actor = get_actor_ref_from_ped(PLAYER::PLAYER_PED_ID());
Run Code Online (Sandbox Code Playgroud)
将调用复制构造函数来复制函数返回的值.如果要捕获引用,则需要声明引用.
Actor & actor = get_actor_ref_from_ped(PLAYER::PLAYER_PED_ID());
^^^^^^^ reference variable
Run Code Online (Sandbox Code Playgroud)
当您找不到对象时,您的函数中也有未定义的行为. return Actor::Actor();正在返回一个在函数退出时被销毁的对象.如果要返回一个空对象,可以在函数中创建一个静态对象,然后返回该对象,因为它仍然存在.有关无法返回临时的原因的详细信息,请参阅:本地变量的内存是否可以在其范围之外访问?
另一种选择是将迭代器返回到元素,如果没有找到元素,则返回actors.end().然后在你的调用者中,你将检查返回的迭代器是否等于actors.end().这需要一些重写.
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |