]> git.notmuchmail.org Git - notmuch/commitdiff
Fix lifetime-maintenance bug with std::string and c_str()
authorCarl Worth <cworth@cworth.org>
Thu, 22 Oct 2009 06:01:17 +0000 (23:01 -0700)
committerCarl Worth <cworth@cworth.org>
Thu, 22 Oct 2009 06:20:18 +0000 (23:20 -0700)
Here's more evidence that C++ is a nightmare to program---or that
I'm smart enough to realize that C++ is more clever than I will
ever be.

Most of my issues with C++ have to do with it hiding things from
me that I'd really like to and expect to be aware of as a C
programmer.

For example, the specific problem here is that there's a
short-lived std::string, from which I just want to copy
the C string. I try to do that on the next line, but before
I can, C++ has already called the destructor on the std::string.

Now, C++ isn't alone in doing garbage collecting like this.
But in a *real* garbage-collecting system, everything would
work that way. For example, here, I'm still holding a pointer
to the C string contents, so if the garbage collector were
aware of that reference, then it might clean up the std::string
container and leave the data I'm still using.

But that's not what we get with C++. Instead, some things are
reference counted and collected, (like the std::string), and
some things just aren't (like the C string it contains). The
end result is that it's very fragile. It forces me to be aware
of the timing of hidden functions. In a "real" system I wouldn't
have to be aware of that timing, and in C the function just
wouldn't be hidden.

message.cc

index 8ca8fdee1871b0f10f7700477e1e3da76f0553b4..24dbae91b17c962640d59c400de05cbe8122d48a 100644 (file)
@@ -176,14 +176,14 @@ notmuch_thread_ids_t *
 notmuch_message_get_thread_ids (notmuch_message_t *message)
 {
     notmuch_thread_ids_t *thread_ids;
-    const char *id_str;
+    std::string id_str;
 
     thread_ids = talloc (message, notmuch_thread_ids_t);
     if (unlikely (thread_ids == NULL))
        return NULL;
 
-    id_str = message->doc.get_value (NOTMUCH_VALUE_THREAD).c_str ();
-    thread_ids->next = talloc_strdup (message, id_str);
+    id_str = message->doc.get_value (NOTMUCH_VALUE_THREAD);
+    thread_ids->next = talloc_strdup (message, id_str.c_str ());
 
     /* Initialize thread_ids->current and terminate first ID. */
     notmuch_thread_ids_advance (thread_ids);