Copying a C++ class with a member variable of reference type

后端 未结 7 2344
清酒与你
清酒与你 2020-12-30 06:06

I\'ve a class which stores a reference to its parent, the reference is passed in the constructor. If I try to copy an instance I get an error \"error C2582: \'operator =\' f

相关标签:
7条回答
  • 2020-12-30 06:29

    I would make it a boost::shared_ptr. You can be pretty rough with these and they take care of themselves. Whereas using a raw pointer means tha you have to worry about that object being kept alive

    0 讨论(0)
  • 2020-12-30 06:31

    I don't recommend this at all

    but if you are really gung ho about doing this:

    #include <new>
    
    MyClass::MyClass(const MyClass &rhs): parent(rhs.parent)
    {
    }
    
    MyClass &MyClass::operator=(const MyClass &rhs)
    {
        if (this!=&rhs)
        {
            this->~MyClass();
            new (this) MyClass(rhs);
        }
    
        return *this;
    }
    
    0 讨论(0)
  • 2020-12-30 06:41

    Yes, if you need to support assignment, making it a pointer instead of a reference is nearly your only choice.

    0 讨论(0)
  • 2020-12-30 06:41

    You need to implement a copy constructor and initialize the reference in that copy constructor, to point to the same reference as the original object.

    0 讨论(0)
  • 2020-12-30 06:46

    There is a way to do it and still use a reference, use a reference_wrapper. So

        T& member;
    

    becomes

        std::reference_wrapper<T> member;
    

    Reference wrappers are basically just re-assignable references.

    0 讨论(0)
  • 2020-12-30 06:48

    As mentioned by others, using std::reference_wrapper can be used. The helper functions std::ref() and std::cref() can be used, too. Unlike other postings, C++03 introduced reference_wrapper, ref() and cref() in the namespace std::tr1, so you have options if you're not using C++11 or beyond.

    0 讨论(0)
提交回复
热议问题