Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String::New: what is it?

I am from a Java background and is learning C++. I encountered the following C++ code:

String source = String::New("'Hello' + ', World'"); 

As what I understand so far, this should be a call to static member function 'New' of class 'String'. But, I've searched through the whole header file defining 'String', there is not any static member named 'New' in the String class or its super classes. Is there any special meaning attached to String class or the New member function in C++?

like image 233
JavaMan Avatar asked Nov 29 '22 19:11

JavaMan


1 Answers

You are correct. That is calling the static method New on the String class.

C++ (or STL) doesn't have a native String class, there is a string class, but it doesn't have a ::New method. You'll have to make sure you're reading the right documentation :)

It's possible that it's inherited from a base-class, so make sure you check if String is part of an inheritance hierarchy.

Here's the deal with v8's String. It's interesting.

There are two implementations:

  • v8::String - the externally visible one (Here is doxygen documentation showing the class hierarchy).
  • v8::internal::String - the internal representation.

Browsing the internal String source code, String is indeed a heap allocated object representing a Javascript string.

It turns out that Google Code's UI is broken (maybe they have a maximum character count?). The v8::internal::HeapObject source code should be in src/objects.h, but the file is truncated. And the externally visible v8::String source code should be in include/v8.h, but it too is truncated.

You can download the source and view the files. Here is what it says:

/**
 * A JavaScript string value (ECMA-262, 4.3.17).
 */
class V8EXPORT String : public Primitive {
 public:
   ...

 /**
   * Allocates a new string from either utf-8 encoded or ascii data.
   * The second parameter 'length' gives the buffer length.
   * If the data is utf-8 encoded, the caller must
   * be careful to supply the length parameter.
   * If it is not given, the function calls
   * 'strlen' to determine the buffer length, it might be
   * wrong if 'data' contains a null character.
   */
  static Local<String> New(const char* data, int length = -1);

  /** Allocates a new string from utf16 data.*/
  static Local<String> New(const uint16_t* data, int length = -1);

  ...
};
like image 63
Stephen Avatar answered Dec 18 '22 21:12

Stephen