return by reference or pointer and check for null?

I have a class :

class A
{
  private:
    vector<int> x;
  public:
     const vector<int>& immutable_data() {
         return x;
      }
      vector<int>* mutable_data() {
          return &x;
      }
}

Now if i use this class , in my code , do i have to check if the pointer returned by the mutable_data() is null or not (given that i know the structure of this class). Personally i think i don't have to because i know there exist a secondary api which returns a const reference and so my pointer can never be null (I can't imagine of a scenario where this function would return me null ,even if it somehow does returns null, what would be the behavior of the const ref version in that case). Or should i say that i know its an address of an existing object on stack , so it cannot be null ? Is this the correct way to think or reason about this ? If any one thinks the other way , please give some example code.

For a more common case scenario in production code : if i use protocol buffers , i already know the generated code for my message templates (for eg: repeatedfields which are like stl containers), but do i still need to do null check every time i want to use the mutable api because they always return either by pointer or const reference.

returning by reference is not what i am looking for.


do i have to check if the pointer returned by the mutable_data() is null or not (given that i know the structure of this class)

In general, design elements like "have to check the pointer" depends on one of two things:

  • Does your design need to be provably safe?
  • If not, then does the design of A::mutable_data() dictate that it won't return null ?
  • If (1), then you should invest in the kind of SAT-solver based tools which can test statically that your code won't access invalid memory.

    If (2), I recommend that you consider the concept of Design by Contract -- it is a powerful one. If A::mutable_data() 's interface is specified not to return null , then it returning null would be a design defect in A::mutable_data() .


    Returning a null pointer usually means "I don't have any data for you". If the class will always have data, then, by design, the function will never return a null pointer. If that's the case, then code that uses the function does not need to check for null pointers. That's one of the guarantees that the function makes: "I won't ever return a null pointer".

    链接地址: http://www.djcxy.com/p/20786.html

    上一篇: 我在哪里可以找到当前的C或C ++标准文档?

    下一篇: 通过引用或指针返回并检查null?