CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    130

    [RESOLVED] Copy constructor does not get called when assigning reference to a non reference var!

    Code:
    class Dispatcher
        {
    
            //Dispatcher callback.
            template<typename T>
            using DispatchCallback = std::function<void(T&)>;
    
    
    
            public:
    
            //Constructor.
            Dispatcher(Event &e) 
            {
                m_event = e;
            }
            
            //Dispatch.
            template<typename T>
            void Dispatch(DispatchCallback<T> callback)
            {
                //Call the callback function.
                if (m_event.GetType() == T::GetStaticType())
                    callback( *(T *)&m_event );
            }
    
    
            private:
            Event m_event;
        };
    In the code above, when the Dispatcher() constructor gets called the m_event = e; does not work. The copy constructor of e is not getting called.

    Is this an expected behavior? I know that when you pass references the idea is that the copy constructor does not get called but I thought that this only works when you assign a reference to another reference like this:
    Code:
    //Copy Constructor should not get called here.
    Event &new_ref = other_reference;
    But when you do something like this:
    Code:
    //Copy Constructor should be called here, isn't it?
    Event new_event = other_reference;
    Last edited by babaliaris; September 5th, 2020 at 06:15 AM.

  2. #2
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    130

    Re: Copy constructor does not get called when assigning reference to a non reference

    Never mind my mistake... The reason wasn't the copy constructor. In the Dispatcher(Event &e) I was passing an instance of MouseMovedEvent which is a subclass of Event.
    But because inside the dispatcher I was assigning it to an Event type, the copy constructor of the Event class was getting called instead of the copy constructor of MouseMovedEvent.
    I fixed it by changing in the dispatcher:

    Code:
    private:
            Event m_event;
    to

    Code:
    private:
            Event &m_event;
    so I will keep track the actual reference instead.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured