对于此代码
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.
更多推荐
发布评论