While following Add unique_ptr with custom deleter as class member I found that smart pointers were already implemented for GLib as g_autoptr
- see GLib - Automatic Cleanup for details. Instead of:
#include <glib.h>
#include <memory>
GError* error = nullptr;
std::unique_ptr<GDBusConnection, decltype(&g_object_unref)> conn(g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error), &g_object_unref);
if (!conn) {
print"Couldn't get bus: %s", error ? error->message : "unknown error");
g_clear_error(&error);
}
I can just do:
#include <glib.h>
g_autoptr(GError) error = nullptr;
g_autoptr(GDBusConnection) conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error);
if (!conn) {
print"Couldn't get bus: %s", error ? error->message : "unknown error");
}
But if I try to do this as part of a class:
#include <glib.h>
class YourClass {
YourClass();
~YourClass();
...
private:
g_autoptr(GDBusConnection) _conn;
};
YourClass::YourClass() {
g_autoptr(GError) error = nullptr;
_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error);
if (!_conn) {
print"Couldn't get bus: %s", error ? error->message : "unknown error");
}
}
I get an error from gcc:
error: 'cleanup' attribute ignored [-Werror=attributes]
| g_autoptr(GDBusConnection) _conn;
Can g_autoptr
not be used in a class declaration?
g_autoptr
can't be used to declare class member variables. It's intended to use only in local scopes.
g_autoptr
is not a smart pointer in terms of RAII. This is a macro that uses compiler specific extensions for registering cleanup handlers in function local scopes. This limits g_autoptr
to use only with a single assignment. Reassignment doesn't free a previously assigned pointer.