我一直在玩std :: vector来了解何时构造,破坏,复制构造和移动构造对象.为此,我编写了以下程序
I have been playing around with std::vector to understand when objects are constructed, destructed, copy constructed and move constructed. To so do, I have written the following program
#include <iostream> #include <vector> class Test { public: Test() { std::cout << "Constructor called for " << this << std::endl; } Test(const Test& x) { std::cout << "Copy Constructor called for " << this << std::endl; } Test(Test&& x) { std::cout << "Move Constructor called for " << this << std::endl; } ~Test() { std::cout << "Destructor called for " << this << std::endl; } }; int main() { std::vector<Test> a( 1 ); a.resize(3); return 0; }调整a的大小时,将发生重新分配.我的猜测是将对象a [0]构造为新的a [0].但是,对于libc ++和libstdc ++,似乎调用了复制构造函数,而不是move构造函数.这样的行为有什么理由吗?
When a is resized, reallocation happens. My guess would have been that the object a[0] is moved constructed to the new a[0]. But, with libc++ and libstdc++, it seems that the copy constructor is called and not the move constructor. Is there any reason for such a behaviour?
推荐答案我刚刚找到了问题的答案.必须将move构造函数声明为no,否则必须这样做.完成此类更改后
I just found the answer to the question. The move constructor has to be declared noexcept to do so. When such a change has been done
Test(Test&& x) noexcept { std::cout << "Move Constructor called for " << this << std::endl; }将调用move构造函数.
the move constructor is called.
更多推荐
在std :: vector上调整大小不会调用move构造函数
发布评论