可能重复:
Does an exception use move semantics when thrown in C++11?
我想知道为什么throw
在适当的时候不调用移动构造函数。这是我的编译器(Visual Studio 2010/2012)中的缺陷还是标准不允许?在后一种情况下,理由是什么?
以下是我希望调用move构造函数的示例,但是使用了复制构造函数。
#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()