【问题标题】:Code calls copy ctor where it normally had to call move ctor代码在通常必须调用 move ctor 的地方调用 copy ctor
【发布时间】:2013-09-14 17:14:00
【问题描述】:

我所拥有的基本上是一个 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”类没有复制ctor,但“addView”试图调用它!?

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

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

解决方案: ScSetupPage3 没有默认移动 ctor,因为它声明了一个非原始 ctor。因此,即使它的成员可以被移动甚至声明了一个 move-ctor,它也会在缺少适当的 ctor 时被复制而不被移动。

【问题讨论】:

  • 该类是否有移动复制构造函数?
  • 谢谢老兄,这就是解决方案!问候
  • 啊,int i; // declares an int called "i"学校的cmets...

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


【解决方案1】:

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

【讨论】:

  • 但即使用 std::move 替换我的演员也无济于事:(
【解决方案2】:

当 juanchopanza 询问 ScSetupPage3 是否声明了移动 ctor 时。我看到了,它确实没有:

ScSetupPage3 没有默认移动 ctor,因为它声明了一个非原始 ctor。因此,即使它的成员可以被移动甚至声明了一个 move-ctor,它也会被复制而不是在缺少适当的 ctor 时移动。

【讨论】:

    猜你喜欢
    • 2019-11-09
    • 2013-08-18
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多