本文介绍了在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构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:30