MWright
MWright

Reputation: 1711

Deep Copying const pointer to const Object

I have an object constructor that takes in a const pointer to a const object

A::A( const B* const ex): m_B(B){};

where m_B:

const B* const m_B;

I am now trying to create a copy constructor and assignment operator I have tried the following without any luck.

Copy Constructor:

A::A( const A& cpy): *m_B(*cpy.m_B) {}

This does not work...how do I approach this? Assignment Operator:

A& A::operator=(const A& rhs) {

 *m_B = *rhs.m_B // I know this won't work because const cannot be assigned 
                 // error: assignment of read-only data-member
}

Any ideas how to solve this problem?

Upvotes: 0

Views: 2364

Answers (4)

Mikhail Vorotilov
Mikhail Vorotilov

Reputation: 21

The "placement new" operator can be useful when assigning objects that have const pointers.

class ref
{
public:
  // Normal constructor creates new immutable reference.
  ref(const char* const ptr, size_t len): m_ptr(ptr),m_len(len) {}
  // Copy constructor creates new copy of existing immutable reference.
  ref(const ref& o): m_ptr(o.m_ptr),m_len(o.m_len) {}
  // Assignment operator replaces existing immutable reference with another one.
  // Previous reference is gone.
  ref& operator=(const ref& o) { new (this) ref(o.m_ptr, o.m_len); return *this; }
private:
  const char* const m_ptr;
  size_t m_len;
}

Upvotes: 0

Xeo
Xeo

Reputation: 131789

If you want deep copies anyways, why do you have a pointer? Just have a raw object.

class B{
  // ...
};

class A{
  const B _b;
public:
  A(A const& other)
    : _b(other._b) {}

private:
  // no assignment operator, since const objects can't be reassigned
  A& operator=(A const&); // undefined
};

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

The assignment operator might have to create a new instance with new:

A& A::operator=(const A& rhs) {
    m_B = new B(rhs.m_B);
    return *this;
}

Of course, you have to keep track of this, so you can delete the pointer if you allocate it. If you don't want to keep track, use new in the constructor as well.

Or even better, use the new shared_ptr to not have to care about pointers much at all.

Upvotes: 0

fefe
fefe

Reputation: 3432

Your problem is, constructors don't have the return value.

And assignment operator is operator=, not operator().

In your constructor, you took a pointer and saved pointer, not the contents of object the pointer points to. If you take this semantics, you should only copy pointers instead of copying the content: (Or do you have something else to achieve?)

class B;

class A {
public:
    const B* m_b;
    A( const B* const ex): m_B(ex){};

    //copy constructor
    A(const A& cpy): m_B(cpy.m_B){};
    //assignment operator
    A& operator=(const A&cpy) {m_B = cpy.m_B;};
};

Upvotes: 0

Related Questions