3

I'm trying to provide a by-reference getter to a list of objects in a class. My setup looks something roughly like this:

class c_Container
{
public:
    c_Item* Get(int uid);
private:
    c_Item itemList[10];
}

class c_Item
{
public:
    int uid;
}

c_Item* c_Container::Get(int uid)
{
    for (int i = 0; i < 10; i++)
    {
        if (itemList[i].uid == uid)
        {
            return &itemList[i];
        }
    }

    return NULL;
}

This is a simplistic example showing usage, usually a c_Item object would have other methods that would do other things. We'd want to obtain the c_Item object from itemList by reference or by address so that we can directly modify it.

When compiling, I get a lint error something like "Exposing low access member 'itemList'". If I try to return by reference instead of returning a pointer, I get the same thing. I guess I understand why, but I can't conceive of a better way to obtain an object from a container class like this by reference. I can fix the error by making itemList public, but that seems like unnecessary access.

Outside of creating wrapper methods in c_Container for all of c_Item's methods (which seems redundant), is there a better way to handle a situation like this?

3
  • Post actual code (e.g. the definition of c_Container). You seem to have some syntax error, but we cannot help you without actual code. Jul 12, 2013 at 18:16
  • Maybe I'm misunderstanding, but what other information would you need? Also, I don't think there's a syntax error because I'm getting a Lint warning, which implies the code was parsed correctly, right?
    – slain
    Jul 12, 2013 at 18:26
  • I overlooked that it was a lint warning which makes this a little subjective (i.e. you don't have to make your lint checker happy). I don't see why c_Container::Get would need to return a pointer and not a reference, but that's unrelated to the warning. I guess it would complain about your own implementation of std::list for the same reason ... Jul 12, 2013 at 18:34

1 Answer 1

4

Container classes are an exception to the general rule that you should not provide public access to private members (by returning a pointer or reference in a getter).

However, a lint tool is not smart enough to determine if the container exception should apply to your Get method or not, so it tries to make the safe assumption and generates a warning. Most lint tools can be given additional information through source code annotations. Check the documentation for your tool to see how it can be informed that the warning for this function is a false-positive and should be suppressed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.