Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there conditions under which using "__attribute__((warn_unused_result))" will not work?

I have been trying to find a reason why this does not work in my code - I think this should work. Here is an excerpt from a header file:

#define WARN_UNUSED     __attribute__((warn_unused_result))

class Trans {

    Vector GetTranslation() const WARN_UNUSED {
        return t;
    }

};

So my question is: why don't I get a warning when I compile code with something like:

Gt.GetTranslation();

?

Thanks for the help.

like image 822
lightmatter Avatar asked Aug 03 '11 22:08

lightmatter


1 Answers

The purpose of this attribute is intended (but not exclusively) for pointers to dynamically allocated data.

It gives a compile-time garantee that the calling code will store the pointer in a variable (may as a parameter to a function too ,but that I'm not certain of) en thereby delegates the responsibility of freeing\releasing\deleting the object it points to.

This in order to prevent memory leakage and\or other lifetime controlling aspects.

for instance ,if you call malloc( ... ) without storing the pointer ,you are not able to free it it afterwards. (malloc should have this attribute)

If you use it on function return an object ,than the mechanism is meaningless because the object that is returned is stored in a temporary and may be copied to a non-temporary variable (might be optimized out) and will always be destructed (because it will.

BTW , it's not particulary usefull for returned references (unless you code is aware of it and requires some kind of release mechanism) ,since the referenced object doesn't get destructed when going out of scope.

like image 171
engf-010 Avatar answered Oct 25 '22 02:10

engf-010