更改对象的"this"指针以指向其他对象 [英] Change 'this' pointer of an object to point different object
问题描述
class C{
//methods and properties
}
void C::some_method(C* b){
delete this;
this = b;
}
这使我在编译时出现以下错误:
This gives me follwing error when compiling:
error: lvalue required as left operand of assignment
我的意图:假设存在类C的对象a和b.类C的内容可能非常庞大,并且逐字段复制可能会非常昂贵.我希望以一种经济的方式将" a
"的所有内容替换为" b
".
My intention:
Say there are objects a and b of class C. The contents of the class C can be very huge and field by field copying can be very costly. I want all the contents of 'a
' to be replaced by 'b
' in an economical way.
默认副本构造函数将执行预期的任务吗?
Will default copy constructor do the intended task?
我发现了一个叫做移动构造函数"的东西 http://akrzemi1.wordpress.com/2011/08/11/move-构造函数/
I found something called 'move constructor' http://akrzemi1.wordpress.com/2011/08/11/move-constructor/
也许,它可能会达到我想要的效果.
Perhaps, it might get the effect that I want.
推荐答案
this
指针是指向要在其上下文中工作的对象的隐式指针,您不能重新分配它.
The this
-pointer is an implicit pointer to the object in whose context you are working, you cannot reassign it.
根据Stroustrup的圣经(我拥有的C ++编程语言,第三版),此
表示为
According to Stroustrup's bible (The C++ Programming Language, 3rd edition I have) this
is expressed as
C * const this
表示您有一个指向类 C 的常量指针,因此,如果您尝试更改它,编译器将抱怨.
meaning you have a constant pointer to your class C, so the compiler will complain if you try to change it.
正如我所纠正的,上述表达式不能完全正确地描述 this
,因为 this
实际上是一个右值.
As I was corrected, the above mentioned expression does not describe this
fully correctly, for this
is actually an rvalue.
这篇关于更改对象的"this"指针以指向其他对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!