C++ DAL - Return Reference or Populate Passed In Reference

后端 未结 2 501
天涯浪人
天涯浪人 2021-01-06 00:46

[EDIT 1 - added third pointer syntax (Thanks Alex)]

Which method would you prefer for a DAL and why out of:

Car& DAL::loadCar(int id) {}
bool DAL         


        
相关标签:
2条回答
  • 2021-01-06 01:00

    The second is definitely preferable. You are returning a reference to an object that has been new'd. For an end user using the software it is not obvious that the returned object would require deleting. PLUS if the user does something like this

    Car myCar = dal.loadCar( id );
    

    The pointer would get lost.

    Your second method therefore puts the control of memory on the caller and stops any weird mistakes from occurring.

    Edit: Return by reference is sensible but only when the parent, ie DAL, class has control over the lifetime of the reference. ie if the DAL class had a vector of Car objects in it then returning a reference would be a perfectly sensible thing to do.

    Edit2: I'd still prefer the second set up. The 3rd is far better than the first but you end up making the caller assume that the object is initialised.

    You could also provide

    Car DAL::loadCar(int id);
    

    And hope accept the stack copy.

    Also don't forget that you can create a kind of null car object so that you return an object that is "valid"ish but returns you no useful information in all the fields (and thus is obviously initialised to rubbish data). This is the Null Object Pattern.

    0 讨论(0)
  • 2021-01-06 01:02

    Since you are anyways allocating objects on heap, why not to consider Car * LoadCar() which returns NULL if problem occurs. This way you have no restrictions with reference types (each reference must be initialized) and also have means to signal the error case.

    0 讨论(0)
提交回复
热议问题