GNOME Bugzilla – Bug 645852
Uncopiable structs/structs with explicit copy constructor
Last modified: 2014-07-26 08:03:42 UTC
Sometimes it would be nice to have the structs that are not copiable or have copy contructor and have destructor. Using it instead of class allows the gcc in RAII to optimize members to registers. For example (I know it is oversimplification): struct DatabaseTransaction { public DatabaseTransaction (Connection conn) { this.conn = conn; conn.begin (); } public string query (string q) { return conn.send (q); } ~DatabaseTransaction () { conn.commit (); } private Connection conn; }
You can specify copy_function to CCode and then add your copy() method like this: [CCode (copy_function = "database_transaction_copy")] struct DatabaseTransaction { public DatabaseTransaction copy () { } } But maybe I have misunderstood your request.
Sorry for late response - I'm during my exam session. I've tried it before posting bug and it doesn't work: % cat test.vala [CCode (copy_function = "database_transaction_copy")] struct DatabaseTransaction { public DatabaseTransaction () { depth = 0; } public DatabaseTransaction copy () { stdout.printf ("copy\n"); DatabaseTransaction tran = this; tran.depth += 1; return tran; } public int depth; } int main () { DatabaseTransaction c1 = DatabaseTransaction (); DatabaseTransaction c2 = c1; stdout.printf ("%d\n", c2.depth); return 0; } % valac test.vala test.vala:7.3-7.33: warning: method `DatabaseTransaction.copy' never used public DatabaseTransaction copy () { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Compilation succeeded - 1 warning(s) % ./test 0
(In reply to comment #2) > DatabaseTransaction tran = this; This line is incorrect but it should result in infinite recursion.
*** This bug has been marked as a duplicate of bug 733110 ***