忽略“接收临时地址”错误(Ignore “taking address of temporary” error)

编程入门 行业动态 更新时间:2024-10-27 08:26:04
忽略“接收临时地址”错误(Ignore “taking address of temporary” error)

对于此代码

struct test {}; test f() { return test(); } void print(test *x) {} int main() { print(&f()); print(&test()); }

gcc-4.6发出两个“临时[-fpermissive]”错误的地址。 这是在4.6中引入的,gcc-4.5可以编译它。

原因非常清楚并且有很好的记录。 问题是它是遗留代码,并且为了编译,我们必须使其工作,因此,围绕文件和/或代码部分执行#pragmas以使用-fpermissive编译它们。 假设客户坚持不修改现有代码 (即使用&f()或&test()调用print()的事实不能更改,一般不会更改源文件)。 换句话说,这种或那种方式被编译,唯一的选择是或多或少的痛苦。

所以问题是 - 是否有任何可能的解决方法可以让它在许多地方不做任务的情况下工作? -W标志,C ++技巧等

For this code

struct test {}; test f() { return test(); } void print(test *x) {} int main() { print(&f()); print(&test()); }

gcc-4.6 emits two "taking address of temporary [-fpermissive]" errors. This was introduced in 4.6, gcc-4.5 could compile it.

The reason is pretty clear and well documented. The problem is that it is a legacy code and, to compile, we have to make it work, thus, doing #pragmas around files and/or parts of code to compile them with -fpermissive. Let's say, customers are adamant not to modify the existing code (i.e. the fact of calling print() with &f() or &test() cannot be changed, not source files in general). In other words, one way or another this will be compiled, the only choice is more or less pain.

So the question is - are there any possible workarounds to make it work without doing -fpermissive in lots of places? -W flags, C++ tricks, etc.

最满意答案

我的意思是,用&f()或&test()调用print()的事实不能改变。

如果您可以控制类型本身,则可以始终重载引用运算符, operator& ,并从中返回它。 在一般情况下这不是一件好事,但考虑到你正在返回正确类型的正确指针,这是相当安全的。

如果涉及基类,则它变得相当复杂。 您需要使用虚拟运算符重载,并且层次结构中的每个类都需要单独实现它。

What I meant is, the fact of calling print() with &f() or &test() cannot be changed.

If you have control over the type itself, you can always overload the reference operator, operator&, and return this from it. It's not a good thing to do in the general case, but it's fairly safe considering that you're returning the correct pointer of the correct type.

If base classes are involved, then it becomes rather more complicated. You'll need to use a virtual operator overload, and each class in the hierarchy will need to implement it separately.

更多推荐

本文发布于:2023-07-15 05:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110693.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   地址   Ignore   error   temporary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!