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