I had these two functions in my project:
char* V8StringToChar(v8::Handle<v8::String> str);
char* V8StringToChar(v8::Local<v8::Value> val);
I converted them to:
template <class T>
class ArrayDeleter {
public:
void operator () (T* d) const
{ delete [] d; }
};
std::shared_ptr<char> V8StringToChar(v8::Handle<v8::String> str);
std::shared_ptr<char> V8StringToChar(v8::Local<v8::Value> val);
with body as
std::shared_ptr<char> V8StringToChar(Handle<String> str) {
int len = str->Utf8Length();
char* buf = new char[len + 1];
str->WriteUtf8(buf, len + 1);
return std::shared_ptr<char>(buf, ArrayDeleter<char>());
}
std::shared_ptr<char> V8StringToChar(Local<Value> val) {
return V8StringToChar(val->ToString());
}
And every usage of them to (&*V8StringToChar(whatever))
.
And it build perfectly.
And it is causing run time errors.
Is there any cases where this could fail And please provide some good solution ?
std::default_delete<char[]>
(note the[]
characters to specify an array, so it usesdelete[]
)&*
gives you a raw pointer, which can be invalidated when the array is deleted - in your example, that happens immediately, before you can do anything with the pointer. Only do that when your really need a raw pointer, and be very careful to ensure that nothing keeps hold of the pointer.