Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Google not want you to use C++ constructors?

Tags:

c++

v8

     /**
     * A JavaScript value representing a signed integer.
     */
    class V8_EXPORT Integer : public Number {
     public:
      static Local<Integer> New(Isolate* isolate, int32_t value);
      static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
      int64_t Value() const;
      V8_INLINE static Integer* Cast(v8::Value* obj);
     private:
      Integer();
      static void CheckCast(v8::Value* obj);
    };

The above code is from Google's V8 engine. Example initialization of this is:

Handle<Value> x = Integer::New(42);

From what I can see in the source code, they marked the constructor as private and want you to use the New function to create instances of this class. Isn't this against the standard C++ design patterns? Why didn't they just overload the constructor instead of making static functions for creation? This usually the kind of thing you see when people try to port a library from one language to another (the only one I can think of off the top of my head right now is Xamarin's iOS kit).

I've tried to Google around for a name for this type of convention but was unable to find anything on it really.

like image 710
David Zech Avatar asked Feb 14 '23 16:02

David Zech


1 Answers

This is a pattern called "Static Factory Method", which is recommended by Joshua Bloch as Item 1 in "Effective Java". (I am almost sure that Scott Myers has an equivalent Item in "Effective C++", but right now I do not have a copy of the book to check.)

The advantages of creating objects through such a method, instead of the normal constructor, are described by Bloch as:

  • such methods may have a descriptive name
  • unlike constructors, such methods are not required to create an entirely new object, i.e. they can return a previously cached copy of the object.
  • unlike constructors, such methods may also return an object of any subtype of their return type
  • such methods reduce verbosity of parameterized object construction

There are also downsides to this design pattern, it is only a recommendation in certain situations.

Probably, in the case of V8, the second point in the list is most important, in order to speed up construction. I am no V8 expert, but it seems that "event-driven, single-threaded" is its philosophy. When many "event callbacks" want to have one and the same number, all of them get a copy of the same instance of that number.

like image 119
logc Avatar answered Mar 02 '23 16:03

logc