c++ - 代码在通常必须调用 move ctor 的地方调用 copy ctor

标签 c++ c++11 move-semantics

我所拥有的基本上是一个 std::map,其中包含指向 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”的调用方式如下:

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

我的问题是“ScSetupPage3”类没有复制构造函数,但“addView”试图调用它!?

这是错误消息,我的 GNU GCC 给我:

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

解决方案: ScSetupPage3 没有默认的 move 构造函数,因为它声明了一个非原始构造函数。因此,即使它的成员可以 move 甚至声明了 move 运算符(operator),它也会在缺少合适的运算符(operator)时被复制而不是 move 。

最佳答案

std::move 就是您要找的。如果可能的话,它基本上是对右值的转换。

从我发现的一个实现来看,您似乎只是犯了一个小错误,尝试自己进行转换:

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);
} 

关于c++ - 代码在通常必须调用 move ctor 的地方调用 copy ctor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18804291/

相关文章:

c++ - 随机访问迭代器到 char 数组

c++ - std::list 删除中的意外结果 (C++)

c++11 - STL map::insert 是否应该支持 move_iterators 的 move 语义?

c++ - move 语义不完整吗?

c++ - 将监视器显示上的大数字与 MONITORINFOEX 中的 szDevice 进行匹配

c++ - 使用数组添加两个大数

c++ - 为什么初始化构造函数列表参数会出现异常?

c++ - move 构造函数如何在 C++ 中工作?

c++ - 为什么将 char* 传递给此方法会失败?

c++ - 使用 waitKey 暂停和播放视频