- Mastering the C++17 STL
- Arthur O'Dwyer
- 249字
- 2021-07-08 10:20:27
Pitfalls with non-noexcept move constructors
Recall the implementation of vector::resize() from section Resizing a std::vector. When the vector resizes, it reallocates its underlying array and moves its elements into the new array--unless the element type is not "nothrow move-constructible," in which case it copies its elements! What this means is that resizing a vector of your own class type will be unnecessarily "pessimized" unless you go out of your way to specify that your move constructor is noexcept.
Consider the following class definitions:
struct Bad {
int x = 0;
Bad() = default;
Bad(const Bad&) { puts("copy Bad"); }
Bad(Bad&&) { puts("move Bad"); }
};
struct Good {
int x = 0;
Good() = default;
Good(const Good&) { puts("copy Good"); }
Good(Good&&) noexcept { puts("move Good"); }
};
class ImplicitlyGood {
std::string x;
Good y;
};
class ImplicitlyBad {
std::string x;
Bad y;
};
We can test the behavior of these classes in isolation using a test harness such as the following. Running test() will print "copy Bad--move Good--copy Bad--move Good." What an appropriate mantra!
template<class T>
void test_resizing()
{
std::vector<T> vec(1);
// Force a reallocation on the vector.
vec.resize(vec.capacity() + 1);
}
void test()
{
test_resizing<Good>();
test_resizing<Bad>();
test_resizing<ImplicitlyGood>();
test_resizing<ImplicitlyBad>();
}
This is a subtle and arcane point, but it can have a major effect on the efficiency of your C++ code in practice. A good rule of thumb is: Whenever you declare your own move constructor or swap function, make sure you declare it noexcept.
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- Elasticsearch Server(Third Edition)
- 利用Python進(jìn)行數(shù)據(jù)分析(原書第3版)
- Getting Started with Greenplum for Big Data Analytics
- Integrating Facebook iOS SDK with Your Application
- Mastering C++ Multithreading
- Kivy Cookbook
- C指針原理揭秘:基于底層實現(xiàn)機(jī)制
- Python Programming for Arduino
- 進(jìn)入IT企業(yè)必讀的324個Java面試題
- 軟件設(shè)計模式(Java版)
- Design Patterns and Best Practices in Java
- ASP.NET Core 2 High Performance(Second Edition)
- Mastering Magento Theme Design
- Python程序設(shè)計