Project

General

Profile

Actions

Bug #3368

closed

Code style rule 3.11 is wrong

Added by Davide Pesavento almost 9 years ago. Updated almost 9 years ago.

Status:
Closed
Priority:
Low
Category:
Docs
Target version:
Start date:
Due date:
% Done:

100%

Estimated time:

Description

Rule 3.11 states the following:

When checking if shared_ptr points to an object, explicit static_cast<bool> must be used.
shared_ptr in C++11 (unlike boost::shared_ptr) does not have implicit conversion to bool.

This is simply wrong. The fact that operator bool() is declared explicit in std::shared_ptr does NOT matter in a boolean context. This is true practically every time a shared_ptr is checked for validity.

The idiomatic way is:

shared_ptr<T> ptr;
if (ptr) { ... }
// OR
if (ptr == nullptr) { ... }
// OR
if (ptr != nullptr) { ... }
// etc...

Moreover, if the implicit conversion isn't possible (when not in a boolean context), the compilation will fail, so there's really no reason why this has to be a code style rule.

Actions #1

Updated by Alex Afanasyev almost 9 years ago

I agree. I wrote this rule based on my misunderstanding of implicit conversion and compilation errors I was getting. Unfortunately, I don't remember a specific case of that error.

@Davide, do mind updating it? We could simply remove the rule (but keep the number reserved).

Actions #2

Updated by Davide Pesavento almost 9 years ago

  • Assignee changed from Junxiao Shi to Davide Pesavento
  • Start date deleted (12/22/2015)

Sure.

An example where you get an error is a function return, in that case you need an explicit cast or it won't compile. But even in that case I'd prefer using == nullptr or != nullptr rather than the cast.

bool
foo()
{
  auto ptr = make_shared<T>(...);

  //return ptr; // FAIL
  //return static_cast<bool>(ptr); // OK, but ugly
  return (ptr != nullptr); // OK, better
}
Actions #3

Updated by Davide Pesavento almost 9 years ago

  • Subject changed from Rule 3.11 is wrong to Code style rule 3.11 is wrong
  • Status changed from New to Code review
  • Priority changed from Normal to Low
  • Target version set to v0.4
  • % Done changed from 0 to 100
Actions #4

Updated by Junxiao Shi almost 9 years ago

  • Project changed from NFD to ndn-cxx
  • Category changed from Docs to Docs
  • Target version changed from v0.4 to v0.4
Actions #5

Updated by Alex Afanasyev almost 9 years ago

  • Status changed from Code review to Closed
Actions

Also available in: Atom PDF