Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force returned object to be assigned [duplicate]

Tags:

c++

is there a way, in C++, to force the assignation of the returned value of a function? i.e. if I have a member function foo

class myClass{
    ...
    public:
    T1 foo(T2 x){T1 y; /*something*/ return y;};
}

which I can call in the main() as

myClass obj;
T1 a = obj.foo(x);  //<--

can I make the simpler call

myClass obj;
obj.foo(x);   //<--

(that does not store the returned value) somehow "illegal"?

Alternatively, can I distinguish the definitions of

T1 a = obj.foo(x);
obj.foo(x);

thank you for your time and sorry for my ignorance

like image 203
Acorbe Avatar asked Oct 02 '12 15:10

Acorbe


2 Answers

If you're using g++, you could use

T1 foo(T2 x) __attribute__ ((warn_unused_result));

This will result in a warning though, not an error. But you could probably use some -Werror=* flag to turn it into an error. See here for all the supported function attributes.

like image 94
Tavian Barnes Avatar answered Oct 12 '22 15:10

Tavian Barnes


No, there's no way to force an operation on a returned object.

And no, you can't distinguish between

T1 a = obj.foo(x);
obj.foo(x);

inside the calls (at least not in a portable, standard way. You could hack away with call-stacks and such, but why would you).

like image 33
Luchian Grigore Avatar answered Oct 12 '22 15:10

Luchian Grigore