Unfortunately, the C++ linter (based on
Google’s cpplint), which can be run
explicitly via make lint-cpp, does not currently catch a lot of rules that are
specific to the Node.js C++ code base. This document explains the most common of
these rules:
char* buffer; instead of char *buffer;
if (foo)
bar();or
if (foo) {
bar();
baz();
}Braces are optional if the statement body only has one line.
namespaces receive no indentation on their own.
VeryLongTypeName very_long_result = SomeValueWithAVeryLongName +
SomeOtherValueWithAVeryLongName;Operators are before the line break in these cases.
void FunctionWithAVeryLongName(int parameter_with_a_very_long_name,
double other_parameter_with_a_very_long_name,
...);If that doesn’t work, break after the ( and use 4 spaces of indentation:
void FunctionWithAReallyReallyReallyLongNameSeriouslyStopIt(
int okay_there_is_no_space_left_in_the_previous_line,
...);Long initialization lists are formatted like this:
HandleWrap::HandleWrap(Environment* env,
Local<Object> object,
uv_handle_t* handle,
AsyncWrap::ProviderType provider)
: AsyncWrap(env, object, provider),
state_(kInitialized),
handle_(handle) {Exceptions are simple getters/setters, which are named property_name() and
set_property_name(), respectively.
class FooBar {
public:
void DoSomething();
static void DoSomethingButItsStaticInstead();
void set_foo_flag(int flag_value);
int foo_flag() const; // Use const-correctness whenever possible.
};int FunctionThatDoesSomething(const char* important_string) {
const char* pointer_into_string = important_string;
}class Foo {
private:
int counter_ = 0;
};template <typename T>
class FancyContainer {
...
}- Always avoid C-style casts (
(type)value) dynamic_castdoes not work because RTTI is not enabled- Use
static_castfor casting whenever it works reinterpret_castis okay ifstatic_castis not appropriate
Malloc(),Calloc(), etc. fromutil.habort in Out-of-Memory situationsUncheckedMalloc(), etc. returnnullptrin OOM situations
What it says in the title.
Do
#include "util-inl.h" // already includes util.hinstead of
#include "util.h"
#include "util-inl.h"If you need to throw JavaScript errors from a C++ binding method, try to do it at the top level and not inside of nested calls.
A lot of code inside Node.js is written so that typechecking etc. is performed in JavaScript.
Using C++ throw is not allowed.