Baz
Baz

Reputation: 13125

Copying object with const members to a non const object

I have the following data container:

struct Node
{
    explicit Node(const std::vector<Data>& _data, const Value& _value): data(_data), value(_value)
    {
    }

    const std::vector<Data> data;
    const Value value;
};

I wish to write a mock along these lines:

class MockVisitor: public IVisitor
{
public:
    virtual void operator()(const Node& _node)
    {
        node = _node;
    }

    Node node;
};

However, I'm getting the error:

error C2582: 'operator =' function is unavailable in 'Node'. 

I'm presuming this is because I can only assign to a const Node. Is there anyway for my to cast away this error? Remember this is only a mock class. I'm simply trying to record the value passed into operator()() so I can check it in my unit test.

Upvotes: 1

Views: 92

Answers (2)

BЈовић
BЈовић

Reputation: 64223

Since the member variables data and value are declared as constant, the operator= is deleted. This is the reason you can not use it, hence the compilation error.

This should work :

class MockVisitor: public IVisitor
{
public:
    virtual void operator()(const Node& _node)
    {
        node.reset( new Node( _node ) );
    }

    std::unique_ptr< Node > node;
};

Upvotes: 2

Puppy
Puppy

Reputation: 146910

Your Node class is immutable. It makes no sense to perform this action, since you are attempting to alter the value of the Node you already have in the MockVisitor. If you want to do this consider boost::optional<Node>.

Upvotes: 0

Related Questions