Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 3-4-1 and lifetimes, initialization, and side effects
#1
We have some interesting cases for Rule 3-4-1 which we aren't sure whether they are violations or not. Strictly adhering to the rule of reduced visibility could cause issues regarding lifetimes, initialization, and side effects of a constructor/destructor.

For instance, in the following example, is the intent to require changes to the code so that 'old_value' is not visible after the if body, or is `old_value` considered non-violating?
Code:
void fn(int a) {
    int old_value = a;
    a += 4;
    if (a > 10) {
        a = old_value;
    }
    // ...
}

Similarly, in cases where an object's constructor or destructor contains side effects, such as with a mutex, is the current visibility of 'merge_thread_lock' intended to be a violation?

Code:
void fn(int a) {
    std::unique_lock<std::shared_mutex> merge_thread_lock(global_mutex);
    if (global) {
      global = a;
      merge_thread_lock.unlock();
    }
    // ...
}
Reply
#2
Your first code example is compliant. The intent of the rule was that declarations should be in the smallest existing scope that retains the meaning of the program, and not to imply that new scopes should be created.

You are also right that there are potential problems when an object has constructors/destructors with side-effects. Cases like 'merge_thread_lock' weren't considered when we drafted this rule. This is one of the reasons that this rule has been removed from MISRA C++::2023
Posted by and on behalf of
the MISRA C++ Working Group
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)