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

橙三吉。 提交于 2019-11-30 22:29:52

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!