4

可能重复:
在 C++11 中抛出异常时是否使用移动语义?

我想知道为什么throw在适当的时候不调用移动构造函数。这是我的编译器(Visual Studio 2010/2012)中的缺陷还是标准不允许?在后一种情况下,推理是什么?

以下是我希望调用移动构造函数的示例,但使用了复制构造函数。

#include <iostream>
#include <exception>

class MyException : public std::exception
{
public:
    MyException(const char* theText) throw()
    :   std::exception(theText) {
        try { std::cout << "MyException()" << std::endl; } catch(...) {}
    }

    ~MyException() throw() {
        try { std::cout << "~MyException()" << std::endl; } catch(...) {}
    }

    MyException(const MyException& ex) throw() 
    :   std::exception(ex) {
        try { std::cout << "MyException copy constructor" << std::endl; } catch (...) {}
    }

    MyException& operator=(const MyException& ex) throw() {
        try { std::cout << "MyException assignment operator" << std::endl; } catch (...) {}
        std::exception::operator=(ex);
        return *this;
    }

    MyException(MyException&& ex) throw()
    :   std::exception(std::move(ex)) {
        try { std::cout << "MyException move constructor" << std::endl; } catch (...) {}
    }

    MyException& operator=(MyException&& ex) throw() {
        try { std::cout << "MyException move assignment operator" << std::endl; } catch (...) {}
        std::exception::operator=(std::move(ex));
        return *this;
    }
};



int main(int argc, char* argv[])
{
    try
    {
        //throw MyException("RVO applies here");

        MyException e("Let's try explicitly");
        throw std::move(e); // The copy constructor is called
    }
    catch(std::exception& e)
    {
        std::cout << "Caught std::exception " << e.what() << std::endl;
    }
    return 0;
}

这将打印以下内容

MyException()
MyException copy constructor
~MyException()
Caught std::exception Let's try explicitly
~MyException()
4

0 回答 0