无论我在互联网上阅读哪篇文章,都强烈建议如果我希望我的类与
std::vector
很好地配合(即,std::vector
使用了我的类的移动语义),就应该将移动构造函数声明为“noexcept”(或者noexcept(true)
)。即使作为一项实验,我将其标记为noexcept(false)
,为什么std::vector
还是使用它了呢?#include <iostream>
#include <vector>
using std::cout;
struct T
{
T() { cout <<"T()\n"; }
T(const T&) { cout <<"T(const T&)\n"; }
T& operator= (const T&)
{ cout <<"T& operator= (const T&)\n"; return *this; }
~T() { cout << "~T()\n"; }
T& operator=(T&&) noexcept(false)
{ cout <<"T& operator=(T&&)\n"; return *this; }
T(T&&) noexcept(false)
{ cout << "T(T&&)\n"; }
};
int main()
{
std::vector<T> t_vec;
t_vec.push_back(T());
}
输出:
T()
T(T&&)
~T()
~T()
为什么?我做错了什么吗?
使用CXX_FLAGS编译的gcc 4.8.2:
--std=c++11 -O0 -fno-elide-constructors