在std :: vector上调整大小不会调用move构造函数

编程入门 行业动态 更新时间:2024-10-09 19:13:00
本文介绍了在std :: vector上调整大小不会调用move构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在玩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构造函数

本文发布于:2023-07-09 21:04:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1088205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   大小   std   vector   move

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!