使用 this = new Foo()? 从内部将一个对象的实例设置为另一个对象的实例?

发布于 2024-10-25 04:37:55 字数 335 浏览 8 评论 0原文

我正在使用哈希表并对其进行重新哈希,我只需将所有值放入一个新的哈希表中,然后将执行实例设置为这个新的哈希表。

我不确定是否可能,所以我只想确认是否是这种情况。我正在尝试:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮生面具三千个 2024-11-01 04:37:56

程序无法修改 this 以指向不同的对象。 this 是一个常量指针(即 T* const )。

this = new_foo; // incorrect.

复制分配的数组的最佳/标准方法是什么?

使用*a = *b;不会复制整个数组。您只需将 b 的第一个索引处的值复制到 a 的第一个索引处。请改用 std::copy


int a[] = { 1,2,3,4,5 } ;
int b[5] ;

// To copy element of a to b -

std::copy( a, a+5, b ) ; // you need to include <algorithm> header.

Program cannot modify this to point to a different object. this is a constant pointer ( i.e., T* const ).

this = new_foo; // incorrect.

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 of b to first index of a. Use std::copy, instead.


int a[] = { 1,2,3,4,5 } ;
int b[5] ;

// To copy element of a to b -

std::copy( a, a+5, b ) ; // you need to include <algorithm> header.
甜宝宝 2024-11-01 04:37:56

您无法分配给 this。考虑创建一个静态方法来创建并返回新实例。

You can't assign to this. Consider creating a static method that creates and returns the new instance.

远昼 2024-11-01 04:37:56

我认为错误消息告诉了您需要了解的内容。 this 关键字不是左值,因此您无法对其进行赋值。为什么你不能这样做?:

Foo *old_foo = ...
Foo *new_foo = new Foo();
delete old_foo;
old_foo = new_foo;

或者,如果它确实是一个哈希表,请创建一个“空”方法来遍历元素并将它们全部删除,而不是删除自身。

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?:

Foo *old_foo = ...
Foo *new_foo = new Foo();
delete old_foo;
old_foo = new_foo;

Or, if it's really a hash table, create an "empty" method that walks the elements and deletes them all rather than deleting itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文