10

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

Acorbe
  • 8,367
  • 5
  • 37
  • 66
  • 1
    There's nothing particularly wrong with discarding return values. Also, even if there was such a way - what about `somefunc(obj.foo(x))`? – Cubic Oct 02 '12 at 15:02
  • What are you trying to achieve that makes this necessary? – Martin York Oct 02 '12 at 15:07
  • Why this question is marked as duplicate of a question asked 4 years later? Thanks @iammilind – Acorbe May 30 '18 at 15:00
  • I think, in the linked duplicate, my answer actually answers your Qn. It's possible what you want to achieve. Also from the meta.SE, you may refer: [Should I vote to close a duplicate question, even though it's much newer, and has more up to date answers?](https://meta.stackexchange.com/q/147643/163449) – iammilind May 30 '18 at 15:18

4 Answers4

8

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.

Tavian Barnes
  • 12,477
  • 4
  • 45
  • 118
  • This is very close to what I need. I might be a little un-portable though. I will explore this way btw. thx. – Acorbe Oct 02 '12 at 15:26
3

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).

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

Simple answer is no; however you could "force it":

return smart pointer that is automatically destroyed when has not any references. In destructor throw some exception or make an assert() call. To prevent crash when used correctly, you can use some variable in that class and set it to false when you are sure you dont need object anymore and that will tell destructor to dont throw anything.

Zaffy
  • 16,801
  • 8
  • 50
  • 77
  • 2
    This mechanism is nice, but of course is a sort of "run-time" check. Thank you very much btw. – Acorbe Oct 02 '12 at 15:28
2

There's no way to tell, but good static analysis tools often show warnings if return values are ignored. The one I use which comes with MSVC2010 certainly does.

Benj
  • 31,668
  • 17
  • 78
  • 127