“需要左值作为赋值的左操作数”在奇怪的地方--C++

发布于 2024-12-25 12:15:52 字数 414 浏览 2 评论 0原文

注意:这不是标题中带有此名称的十亿零一个问题的重复。这与指针和非常奇怪的东西有关,而不是意外的 = 而不是 ==

我有一个 C++ 函数,其中有一个名为 outvoid* 参数。我有这一行:

(char*)out=new char[*size];

Where size in a uint32_t*。编译器抱怨:

fundemental_bin_types.h:55:32: error: lvalue required as left operand of assignment

出了什么问题?

NOTE: This is NOT a duplicate of the billion and one questions with this name in the title. This has to do with pointers and very odd stuff, not an accidental = instead of ==.

I have a C++ function in which I have a void* argument called out. I have this line:

(char*)out=new char[*size];

Where size in a uint32_t*. The compiler complains:

fundemental_bin_types.h:55:32: error: lvalue required as left operand of assignment

What is wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

末が日狂欢 2025-01-01 12:15:53

(char*)out 不是左值(out 本身可能是,但转换会改变一些东西),转换属于左值的另一边赋值,并且您将转换为 void 指针而不是 char 指针:

out = (void*) (new char[*size]);

在任何情况下,void* 都可以从其他指针隐式转换,因此您只需:

out = new char[*size];

(char*)out is not an lvalue (out itself may be but the cast changes things), the cast belongs on the other side of the assignment and you're casting to a void pointer rather than a char pointer:

out = (void*) (new char[*size]);

In any case, void* is implicitly convertible from other pointers so you can get away with just:

out = new char[*size];
你曾走过我的故事 2025-01-01 12:15:53

C 指针转换创建左值; C++ 指针强制转换不会,除非强制转换为引用类型。即,应编译以下内容:

(char *&)out= new char[*size];

C pointer casts create an lvalue; C++ pointer casts do not unless you cast to a reference type. I.e., the following should compile:

(char *&)out= new char[*size];
季末如歌 2025-01-01 12:15:53

删除 (char*),因为它在这里没有任何作用。 (或者它有一些您没有解释过的目的。)

如果您有一个 void* 参数,您不能简单地分配给它(以便让调用者看到该指针),就像您可以为 void* 一样& 参数。

Remove the (char*) as it serves no purpose here. (Or it serves some purpose that you haven't explained.)

If you have a void* argument you can't simply assign to it (in order to have that pointer seen by the caller) like you could a void*& argument.

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