Jakob Riedle
Jakob Riedle

Reputation: 2018

Code calls copy ctor where it normally had to call move ctor

What i have is basically a std::map holding pointers to Views.

std::map<string,View*>  myViews;

template<typename T>
bool addView( string assocName , T&& view )
{
    typedef typename std::remove_reference<T>::type T2;
    typedef typename T2::View dummy; // check if T is subclass of 'View'

    // Remove any Current View
    View* &data = myViews[assocName]; // reference to pointer

    if( data )
        delete data; // Delete Current associated view

    // Insert the new View
    data = new T2( std::move(view) ); // <-- Here is the error
}

'addView' is called the following way:

viewSwitcher.addView( "3" , ScSetupPage3() );

My problem is that the class 'ScSetupPage3' doesn't have a copy ctor, but 'addView' tries to call it!?

This is the error msg, my GNU GCC gives me:

error: use of deleted function 'ScSetupPage3::ScSetupPage3(const ScSetupPage3&)'

Solution: ScSetupPage3 doesn't have a default move ctor because it has a non-primitive ctor declared. Hence it will be copied and not moved in lack of an appropriate ctor, even if its members could be moved or even have a move-ctor declared.

Upvotes: 3

Views: 148

Answers (2)

Jakob Riedle
Jakob Riedle

Reputation: 2018

As juanchopanza asked whether ScSetupPage3 had a move ctor declared. I saw, that it indeed hadn't one:

ScSetupPage3 doesn't have a default move ctor because it has a non-primitive ctor declared. Hence it will be copied and not moved in lack of an appropriate ctor, even if its members could be moved or even have a move-ctor declared.

Upvotes: 1

typ1232
typ1232

Reputation: 5607

std::move is what you are looking for. It is basically a cast to an rvalue if possible.

From an implementation I found, it seems you only did a small mistake, by trying to do the cast yourself:

template<class T> 
typename remove_reference<T>::type&&
std::move(T&& a) noexcept
{
  typedef typename remove_reference<T>::type&& RvalRef;
  return static_cast<RvalRef>(a);
} 

Upvotes: 1

Related Questions