Search code examples
c++v8

Where did the function and the variable come from?


Please sorry, I am JavaScript and TypeScript guy, not a c++ one.

But the JS engine V8 is written in c++ and here is a code piece from there:

// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);

In the code above there are two lines. First line contains utf8 function... where does it come from? I didn't see it before in the file and it wasn't imported (or was it)?

Second line contains utf8 variable (right?), though with * modifier which I am not aware of. Where did the variable come from? What is the role of the star modifier?

Sorry for this kind of questions, but at this point I cannot delve into the documentation of one of the most complex languages, which is c++...


Solution

  • utf8 is not a function, but a variable. The snippet (isolate, result) is the arguments passed to its constructor.

    This could be rewritten as follows to be functionally identical, and in a way that is more familiar to a JavaScript programmer:

    auto utf8 = v8::String::Utf8Value(isolate, result);
    

    where auto infers the type of a variable.

    As for the * in *utf8, the meaning of this will depend the implementation. * as a prefix operator can be given a user-defined meaning, though usually it has the semantics of "reach into and get the value from," as with raw pointers and things like std::unique_ptr and std::optional. I'm not familiar with v8 personally. You should look for documentation on the * operator for the v8::String::Utf8Value type, to see exactly what it does.

    You should also be very aware that C++ takes a long time to learn, and it's terribly easy to misunderstand or do things very wrong. If you want to commit to learning C++, I would suggest reading a good C++ book to get a foundational understanding.