Temporary assistance needed

I came across a GCC warning that I want to fix. Basically, I pass a method pointer to a local variable, which in my case is completely normal. I understand why the compiler tells me that this is a potential problem, but in my case this is normal.

How can I get around this in local space? Passing -fpermissive when compiling will cause me not to find future problems. I want to fix this specific problem or get around it.

The code is available here:

 #include <cstdio> class Integer{ public: Integer(int i ){ v = i; }; int value(){ return v; }; private: int v; }; int foo(Integer *i); int main() { foo( &Integer(12) ); } int foo(Integer *i) { std::printf("Integer = %d\n", i->value()); } 

And the compilation gives me:

 $ g++ test-reference.cpp -O test-reference test-reference.cpp: In function 'int main()': test-reference.cpp:15:18: error: taking address of temporary [-fpermissive] $ g++ --version g++ (Ubuntu/Linaro 4.6.3-1ubuntu3) 4.6.3 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 

EDIT:

Using const (as when creating foo take a pointer to const and mark value() as const), you will get the same error.

+8
c ++ gcc pass-by-reference
source share
3 answers
 Integer i(12); foo(&i); 

This eliminates the problem of "taking the temporary address" that you have. You do not pass the address of the local variable (which is indicated above, and in this case is really normal), you capture the address of the temporary one.

Obviously, if foo tries to somehow hold on to this pointer, you will have row problems.

+9
source share

In this case, the GCC is erroneous. Your integer is the rvalue value, and the rvalue address is illegal.

§5.3.1 Unary operators, section 3

The result of unary and operator is a pointer to its operand. the operand must be an lvalue or qualified id.

In this case, Clang gives an error:

 error: taking the address of a temporary object of type 'Integer' [-Waddress-of-temporary] foo( &Integer(12) ); ^~~~~~~~~~~~ 
+4
source share
 template<typename T> const T* rvalue_address(const T& in) { return &in; } 

In my opinion, it should be true if const T* lies like const T& , but this trivial function will easily perform the conversion.

+3
source share

All Articles