Clarification for 7–5–1

Moderators: david ward, misra cpp

Post Reply
pkruk
Posts: 20
Joined: Fri Jul 27, 2007 3:25 pm

Clarification for 7–5–1

Post by pkruk » Mon Jan 12, 2009 9:48 am

A function shall not return a reference or a pointer to an automatic variable (including parameters), defined within the function.
I have a question about reference types. Is the following code compliant or not?

Code: Select all

int global_var;

int & foo(int & ref) {
    return ref;             // Compliant?
    
    int & global_ref = global_var;
    return global_ref;      // Compliant?
    
    int local_var;
    int & local_ref = local_var;
    return local_ref;       // Compliant?
}

int * bar(int & ref) {
    return &ref;            // Compliant?

    int & global_ref = global_var;
    return &global_ref;     // Compliant?
    
    int local_var;
    int & local_ref = local_var;
    return &local_ref;      // Compliant?
}

misra cpp
Posts: 148
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Clarification for 7–5–1

Post by misra cpp » Mon Oct 05, 2015 3:02 pm

In foo() and bar():
  • The first return is compliant with 7-5-1 but breaks 7-5-3.
  • The second return is compliant as the object is global.
  • The third return is non-compliant.
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.7 Declarations (C++)”