在不进行铸造的情况下归还新物体是否有风险? [英] Is returning a new object without casting is risky ?

查看:57
本文介绍了在不进行铸造的情况下归还新物体是否有风险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


请查看下面的代码,并告诉我我做得很对,否则涉及一些风险以及什么样的风险?

Hi,
Please see the below code and please tell me that i am doing perfectly right or there is some risk involve and what kind of risk?

XGGraphicAttribute* XGGraphicAttribute::Create()
{
    return new XGGraphicAttribute;
}



问候
BitsMax



Regards
BitsMax

推荐答案

查看
Looking at the description of the new[^] operator, I would say you are doing it correctly. Since you are returning an object of the type that the Create() function says it will return, you will not need any casting within this code.


如果存在任何风险,则可能该函数的调用者可能无法删除返回的对象,从而导致内存泄漏.
因此,请正确记录该函数(您应该始终这样做),并声明调用方负责清理返回的对象.
If there is any risk it is that the caller of the function may not delete the returned object, creating a memory leak.
So document the function properly (which you should always do) and state that the caller is responsible for cleaning up the returned object.


绝对不需要强制转换,因为new会完全返回您声明为返回类型的类型.也许您将其与malloc()混淆了,它返回了void*?

我唯一想到的就是您可能要更改,那就是从构造函数中捕获可能的异常-如果这是您的Create()函数的目的!例如,您可以做出空头保证(请参见
http://www.gotw.ca/gotw/059.htm [ ^ ]),如下所示:

There is absolutely no casting required as new will return exactly the type you declared as return type. Maybe you are confusing this with malloc(), which returns a void* ?

The only thing I can think of that you might want to change, is catching possible exceptions from the constructor - if that is the purpose of your Create() function! You could for instance make a nothrow guarantee (see http://www.gotw.ca/gotw/059.htm[^]) like this:

XGGraphicAttribute* XGGraphicAttribute::Create() throw() {
   XGGraphicAttribute* result = 0;
   try {
      result = new XGGraphicAttribute;
   }
   catch (std::bad_alloc) {
      // memory allocation failed
      // send some out-of-memory notification
   }
   catch () {
      // contructor failed
      // send some notification, if you want to
   }
   return result;
}



再说一次,最好让这些异常打到调用者上,这会更好.这样,调用者就不会想到永远不会考虑测试结果值的危险-如果仍未捕获到异常,它将立即引起开发人员的注意,并(有希望)导致修复.



Then again, it might be better to just let those exceptions hit the caller instead; that way there is no danger that the caller never thinks to test the result value - if the exception remains uncaught, it will immediately catch the attention of the developer, and (hopefully) lead to a fix.


这篇关于在不进行铸造的情况下归还新物体是否有风险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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