使用 this = new Foo()? 从内部将一个对象的实例设置为另一个对象的实例?
我正在使用哈希表并对其进行重新哈希,我只需将所有值放入一个新的哈希表中,然后将执行实例设置为这个新的哈希表。
我不确定是否可能,所以我只想确认是否是这种情况。我正在尝试:
Foo *new_foo = new Foo();
...
delete this;
this = new_foo;
我知道问题不在于删除行,因为即使没有删除行它也无法工作。这是错误:错误:需要左值作为赋值的左操作数。
另外,作为一个附带问题,复制分配的数组的最佳/标准方法是什么? *a = *b
?显然,我是 C++ 新手,了解它会很有帮助,但不是必需的。
I am working with a hash table and to rehash it, I am simply putting all the values into a new hash table, and then setting the executing instance to this new hash table.
I wasn't sure going into it if that was possible, so I just want to confirm if this is the case. I am trying:
Foo *new_foo = new Foo();
...
delete this;
this = new_foo;
I know the problem isn't the delete line, since it doesn't work even without that. This is the error: error: lvalue required as left operand of assignment.
Also, just as a side question, what's the best/standard way for copying allocated arrays? *a = *b
? I'm new to C++, obviously, and it would be helpful to know, but not necessary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
程序无法修改
this
以指向不同的对象。this
是一个常量指针(即T* const
)。复制分配的数组的最佳/标准方法是什么?
使用
*a = *b;
不会复制整个数组。您只需将b
的第一个索引处的值复制到a
的第一个索引处。请改用std::copy
。Program cannot modify
this
to point to a different object.this
is a constant pointer ( i.e.,T* const
).what's the best/standard way for copying allocated arrays?
Using
*a = *b;
doesn't copy the entire array. You are just copying the value at first index ofb
to first index ofa
. Usestd::copy
, instead.您无法分配给
this
。考虑创建一个静态方法来创建并返回新实例。You can't assign to
this
. Consider creating a static method that creates and returns the new instance.我认为错误消息告诉了您需要了解的内容。
this
关键字不是左值,因此您无法对其进行赋值。为什么你不能这样做?:或者,如果它确实是一个哈希表,请创建一个“空”方法来遍历元素并将它们全部删除,而不是删除自身。
I think the error message is telling you what you need to know. The
this
keyword isn't an lvalue, and therefore you can't assign to it. Why can't you just do this?:Or, if it's really a hash table, create an "empty" method that walks the elements and deletes them all rather than deleting itself.