0

I have a class that has multiple member variables, among which only one is a pointer that requires deep copying. Because of this single pointer I need to define my custom CCTOR and have to copy every single variables manually. Is this a way to avoid this? Of course I could have just used a std::string but that is not the point of this question.

class Foo {
public:
    Foo(const Foo& other) {
        // deep copying c_str
        cout << "Calling copy constructor" << endl;
        c_str = new char[strlen(other.c_str) + 1];
        strcpy(c_str, other.c_str);
        
        // laboriously copying... is there a way to avoid this?
        a = other.a, b = other.b, c= other.c;
    }

private:
    int a, b, c;
    char* c_str;
};
  • Dunno whether there is a known pattern to that but you could define a (probably private or protected) superclass that is trivially copyable and copy that with its default cctor, then deep-copy the additional members defined in this derived class. – Peter - Reinstate Monica Feb 09 '21 at 23:56
  • 2
    Is there any reason why you are not using a `std::string`? It has all that copying built in. – Ted Lyngmo Feb 09 '21 at 23:58
  • 2
    @TedLyngmo Yes: Then they couldn't ask this question! ;-) – Peter - Reinstate Monica Feb 09 '21 at 23:59
  • 4
    @Peter-ReinstateMonica :-) user3884723: The pattern is afaik to separate the pointer from all the other member variables and make a class that deals with that pointer only. Since you're dealing with strings, it'll probably _very_ similar to `std::string`. When that class is ready, the class you now have in the question can have your new class as a member and use the default cctor. – Ted Lyngmo Feb 10 '21 at 00:01
  • 1
    Another idea, if the class meets certain requirements, is to memcpy into `*this`and then simply overwrite the members which need it. – Peter - Reinstate Monica Feb 10 '21 at 00:02
  • Related: [How to use both default and own copy constructor in C++?](https://stackoverflow.com/questions/12423058/how-to-use-both-default-and-own-copy-constructor-in-c). – dxiv Feb 10 '21 at 00:21
  • @TedLyngmo "The pattern is afaik to separate the pointer from all the other member variables and make a class that deals with that pointer only." That's interesting. Is there a name for such pattern? – user3884723 Feb 10 '21 at 00:44
  • @user3884723 [RAII](https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization). Here's [an example](https://godbolt.org/z/vK64G9) of a start of such a class. – Ted Lyngmo Feb 10 '21 at 06:44

0 Answers0