C ++ DAL - 返回引用或填充传递引用 [英] C++ DAL - Return Reference or Populate Passed In Reference

查看:225
本文介绍了C ++ DAL - 返回引用或填充传递引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你最喜欢DAL的方法和原因:

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

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

如果无法找到汽车第一个方法返回null,第二个方法返回false。

If unable to find the car first method returns null, second method returns false.

第二种方法将在堆上创建一个Car对象,并填充从数据库查询的数据。推测(我的C ++非常生锈),这意味着代码如下:

The second method would create a Car object on the heap and populate with data queried from the database. Presumably (my C++ is very rusty) that would mean code along the lines of:

Car& DAL::loadCar(int id)
{
    Car *carPtr = new Car();
    Car &car= *carPtr;
    car.setModel(/* value from database */);
    car.setEngineSize(/* value from database */);
    // etc
    return car;
}

感谢

推荐答案

第二个是绝对优选的。您正在返回对新的对象的引用。对于使用软件的最终用户,返回的对象将不需要删除是不明显的。 PLUS如果用户做这样的事情

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 );

指针将丢失。

因此,第二种方法将对记忆的控制放在调用者上,并阻止发生任何奇怪的错误。

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

编辑:返回引用是合理的,但只有当父,类可以控制引用的生命周期。即如果DAL类有一个Car对象的向量,然后返回一个引用将是一个完全合理的事情做。

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.

您也可以提供

Car DAL::loadCar(int id);

并希望接受堆栈副本。

也不要忘记,你可以创建一个null的汽车对象,使你返回一个有效的ish对象,但返回你没有有用的信息在所有字段(因此显然初始化为垃圾数据)。这是Null对象模式。

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.

这篇关于C ++ DAL - 返回引用或填充传递引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆