2

I'm new to C++ and started playing with references, which led me to the following code:

#include <iostream>
#include <unordered_map>

class Wrapper {
private:
    std::unordered_map<std::string, int> map;
public:
    void add(std::string &key, int value) { map[key] = value; }
    int get(std::string &key) { return map[key]; }
};

class Writer {
private:
    Wrapper wrapper;
public:
    explicit Writer(const Wrapper &wrapper) : wrapper(wrapper) 
    { 
        std::cout << "Writer: " << &wrapper << std::endl; 
    }
    void write(std::string key, int value) { wrapper.add(key, value); }
};

class Reader {
private:
    Wrapper wrapper;
public:
    explicit Reader(const Wrapper &wrapper) : wrapper(wrapper) 
    { 
        std::cout << "Reader: " << &wrapper << std::endl; 
    }
    int read(std::string key) { return wrapper.get(key); }
};

My main function:

int main() 
{
    Wrapper wrapper;
    Writer writer(wrapper);
    Reader reader(wrapper);

    writer.write("key", 123);
    std::cout << "Value: " << reader.read("key") << std::endl;
}

I pass a reference to the same instance of the Wrapper class when I create an instance of Writer and Reader. I expected that the value added by the writer should also be available to the reader, since they use the same wrapper instance. However, the read("key") call returns 0 because the key is unknown.

What am I doing wrong and how can I achieve the desired behavior?

2
  • wrapper(wrapper) is calling the copy constructor. The default implementation of a copy constructor will make a copy. Commented Aug 8, 2022 at 13:58
  • 3
    You pass a reference but wrapper is not a reference in your Reader and Writer classes. Make it so and it should work. Commented Aug 8, 2022 at 14:01

1 Answer 1

7

member variable must also be declared as reference, in both reader and writer

class Writer {
private:
    Wrapper & wrapper;
}


class Reader {
private:
    Wrapper & wrapper;
}
Sign up to request clarification or add additional context in comments.

7 Comments

Pedantry, but a pointer would also work.
I don't like mixing pointer and reference syntax...
Using member variables that are references has serious implications for copy constructor, move constructor, copy assignment, and move assignment. (Meaning that the programmer should be aware of them; not that they shouldn't use reference member variables.)
@Eljay same for a (raw) pointer, but with a pointer the consequences are easier to handle
btw I don't think it is "pedantry". I agree that references as members are rarely the right choice. While this is somewhat opinionated, saying OP "must declare the members as reference" isn't right
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.