将对象传递给C ++函数时的副作用 [英] Side effects when passing objects to function in C++

查看:78
本文介绍了将对象传递给C ++函数时的副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了 C ++:完整的参考书预订了以下内容

I have read in C++ : The Complete Reference book the following


即使通过普通的
按值调用参数传递机制将对象传递给函数,从理论上讲,该机制可以保护
并隔离调用参数,但侧面$ b仍然可能可能会影响
参数的对象发生$ b效果。例如,如果用作参数的对象分配了
内存并在销毁该内存时释放该内存,则当析构函数为
时,该函数内部的本地副本
将释放相同的内存。这将损坏原始对象,并实际上使
失去作用。

Even though objects are passed to functions by means of the normal call-by-value parameter passing mechanism, which, in theory, protects and insulates the calling argument, it is still possible for a side effect to occur that may affect, or even damage, the object used as an argument. For example, if an object used as an argument allocates memory and frees that memory when it is destroyed, then its local copy inside the function will free the same memory when its destructor is called. This will leave the original object damaged and effectively useless.

我不太了解副作用的发生方式。有人可以通过示例帮助我理解这一点吗?

I do not really understand how the side effect occurs. Could anybody help me understand this with an example ?

推荐答案

该段落可能正在讨论这种情况:

That passage is probably talking about this situation:

class A {
  int *p;
public:
  A () : p(new int[100]) {}
  // default copy constructor and assignment
 ~A() { delete[] p; }
};

现在 A 对象用作传递对象值:

Now A object is used as pass by value:

void bar(A copy)
{
  // do something
  // copy.~A() called which deallocates copy.p
}
void foo ()
{
  A a;  // a.p is allocated
  bar(a);  // a.p was shallow copied and deallocated at the end of  'bar()'
  // again a.~A() is called and a.p is deallocated ... undefined behavior
}

这篇关于将对象传递给C ++函数时的副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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