c++ - copy constructor for a class with pointer to a user defined type -


i have seen many examples of copy constructor classes member variables pointer int or char. can advise on right way of writing copy constructor class member ptrb pointer user defined class b please.

is correct:

class {     private:       b *ptrb;     public:       a() { ptrb = new b; }       a(const a& other);       ~a(); }  a::a(const a& other) {   ptrb = new b;   *(ptrb) = *(other.ptrb); } 

and if ptrb defined this:

shared_ptr<b> ptrb; 

then this?

a::a(const a& other) {   ptrb(new b);   *(ptrb) = *(other.ptrb); } 

thanks.

since tagged post "deep-copy" assume want copy constructor that. default copy constructor generated using shared_ptr not deep copy.

i suggest there 2 general forms copying pointer-like member.

deep(const deep& other): ptr(new t(*other.ptr)) {} 

and

shallow(const shallow& other) = default; 

note, shallow copy won't work unique_ptr. design, unique_ptr prevents that.

here example of each, showing difference. nb, using raw version in practice lead memory leak. important point after shallow copy, modifying copy modifies original.

#include <memory> #include <iostream>  template<typename t, typename tptr> struct deep {     tptr ptr;      deep() : ptr(new t) {}      t get() const { return *ptr; }     void set(t t) { *ptr = t; }      deep(const deep& other): ptr(new t(*other.ptr)) {} };  template<typename t, typename tptr> struct shallow {     tptr ptr;      shallow() : ptr(new t) {}      t get() const { return *ptr; }     void set(t t) { *ptr = t; }      shallow(const shallow& other) = default; };  template<typename t> using raw_ptr = t*;  template<typename t> void test(const t& a1) {     auto a2 = a1;     a2.set(a2.get() + 1);     std::cout << a1.get() << " " << a2.get() << std::endl;   }  using std::shared_ptr;  int main() {     deep<int, raw_ptr<int> > rawdeep;     rawdeep.set(1);     test(rawdeep);      deep<int, shared_ptr<int> > shareddeep;     shareddeep.set(1);     test(shareddeep);      shallow<int, raw_ptr<int> > rawshallow;     rawshallow.set(1);     test(rawshallow);      shallow<int, shared_ptr<int> > sharedshallow;     sharedshallow.set(1);     test(sharedshallow); } 

http://ideone.com/nltfuo


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -