Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any gotchas in copy ctor and assignment operator having slightly different semantics?

Please look at the following code and tell me if it's going to cause problems in the future, and if yes, how to avoid them.

class Note
{
   int id;
   std::string text;

public:
   // ... some ctors here...

   Note(const Note& other) : id(other.id), text(other.text) {}

   void operator=(const Note& other) // returns void: no chaining wanted
   {
      if (&other == this) return;
      text = other.text;  
      // NB: id stays the same!    
   }
   ...
};

In short, I want the copy constructor to create an exact copy of an object, including its (database) ID field. On the other hand, when I assign, I want just to copy the data fields. But I have some concerns, since usually the copy ctor and the operator= have same semantics.

The id field is used only by Note and its friends. For all other clients, the assignment operator does create an exact copy. The use case: When I want to edit a note, I create a copy using copy ctor, edit it, and then call save on the Notebook class which manages Notes:

 Note n(notebook.getNote(id));
 n = editNote(n); // pass by const ref (for the case edit is canceled)
 notebook.saveNote(n);

When on the other hand I want to create a completely new note with the same contents as an existing note, I can do this:

 Note n; 
 n = notebook.getNote(id); 
 n.setText("This is a copy");
 notebook.addNote(n);

Is this approach plausible? If not, please point out what the possible negative consequences are! Thanks a lot!

like image 473
Alex Jenter Avatar asked Dec 10 '22 17:12

Alex Jenter


1 Answers

If you want semantics that don't match what's expected from the assignment operator, then don't use it. Instead, disable it by declaring a private operator= and define a function with a name that makes clear what's going on, like copyDataFields.

like image 146
aem Avatar answered Jan 07 '23 14:01

aem