Click here to Skip to main content
15,918,178 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C++
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
	}
}


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.
Posted
Updated 31-May-16 12:06pm

1 solution

Use a reference to MyObject in your for loop:
C++
for (MyObject& object : _objects)

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.
 
Share this answer
 
Comments
xxhatred 31-May-16 18:21pm    
Seems that the & was enough, keeping it in scope
changed to

MyObject* getObjectByMyValue(MyValue value)
{
for (MyObject& object : _objects)
{
if (object.value == value)
{
return object;
}
}
return NULL;
}

void otherFunction()
{
MyObject* object = getObjectByMyValue(something);
if (object != NULL)
{
object->someValue = "something else"; // it DOES change the value
}
else
{
//object not found
}
}

Thank you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900