[英]Is it necessary to use 'new' operator in the following C++ code?
The code is: 代码是:
class base{
base(){}
virtual base* copy()const=0;
virtual ~base(){}
};
class derived:public base{
derived(){}
base* copy()const;
~derived(){}
};
base* derived::copy()const{
return new derived(*this);
}
Is it necessary to use the new
operator in the function copy()
or why the code use the new
operator? 是否有必要使用
new
运算符的功能copy()
或为什么代码中使用new
运营商?
Should I directly return this
pointer, like this: 我应该直接返回
this
指针,如下所示:
const base* derived::copy()const{
return this;// note: this pointer is const.
}
To put it extremely simply, no. 把它非常简单,没有。
The this
keyword in C++ is a small bit of syntactic sugar meaning "pointer to the current instance of this object". C ++中的
this
关键字是一小段语法糖,意思是“指向此对象的当前实例的指针”。
A copy
method, by English-language definition, returns a new object, identical to the first in every way but occupying a different location in memory . 通过英语定义的
copy
方法返回一个新对象,与每个方法中的第一个对象相同,但占用内存中的不同位置 。 Returning this
from a copy
method would, quite naturally, break with this paradigm, because it would be returning a pointer to the object being "copied" . 从一个
copy
方法返回this
,很自然地会打破这个范例,因为它将返回一个指向被“复制”的对象的指针。
your function 你的功能
base* derived::copy()const{
return new derived(*this);
}
seems to be correct - you have to use the "new" Operator here. 似乎是正确的 - 你必须在这里使用“新”运算符。 Otherwise, you would create a local instance (of class derived) and return a pointer to that local instance.
否则,您将创建一个本地实例(派生类)并返回指向该本地实例的指针。 After execution of your method, the local instance will get invalid (because it is out of scope).
执行您的方法后,本地实例将变为无效(因为它超出了范围)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.