从函数返回对象的引用,并修改std :: list中的(原始)对象 [英] Return a reference to object from function, and modify the (original) object which is in a std::list
问题描述
我不习惯C ++。我试图找到(通过函数),然后操作std :: list中对象内的值
有人可以帮忙吗?谢谢。
I'm not used to C++. I'm trying to find (via a function), then manipulate values inside an object that is in a std::list
Can anybody help? Thanks.
MyObject getObjectByMyValue(MyValue value)
{
for (MyObject object : _objects)
{
if (object.value == value)
{
return object;
}
}
throw("");
}
void otherFunction()
{
try
{
MyObject& object = getObjectByMyValue("something");
object.someValue = "something else"; // it doesn't change the value
}
catch (...)
{
//object not found
}
}
我的尝试:
我尝试过使用指针并在找不到时返回NULL,但这不起作用。
我也理解退货对象;在其他函数获取它的时候,引用可能超出了这个范围。
我试过谷歌搜索并找到人们使用new来创建另一个对象的例子,但是如果可能,我不想这样做。
What I have tried:
I've tried using pointers and returning NULL when it isn't found also, but that doesn't work.
I also understand that return object; reference may be out of scope here by the time the other function gets it.
I've tried Googling and found examples where people use new to create another object, but I don't want to do that if possible.
推荐答案
在for循环中使用对MyObject的引用:
Use a reference to MyObject in your for loop:
for (MyObject& object : _objects)
避免了问题超出范围的对象
变量。
但请允许我说这通常不是一个好习惯为未找到条件抛出异常。这使您的代码更难以使用,并导致相当常见的情况不必要的麻烦。在未找到对象的情况下,返回指针和NULL的方法可能更好。通过上述for循环的修正,它将起作用。
That avoids the problem with the object
variable going out of scope.
But allow me the remark that it is usually not a good practice to throw an exception for a "not found" condition. This makes your code more difficult to use and causes unnecessary headaches for a rather common situation. Your approach returning a pointer and NULL in the case that the object has not been found is probably better. And with the above correction of the for loop it will work.
这篇关于从函数返回对象的引用,并修改std :: list中的(原始)对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!