Resize on std::vector does not call move constructor [duplicate]

百般思念 提交于 2019-12-04 03:26:38

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;
}

the move constructor is called.

Just as @InsideLoop's answer said, the move constructor has to be declared "noexcept" to be called.

It is because in the vector::resize() function call stack, we can find move_if_noexcept() is called in function __construct_backward().(see [your library path]/include/c++/v1/memory line:1531)

construct(__a, _VSTD::__to_raw_pointer(__end2-1), _VSTD::move_if_noexcept(*--__end1));

According to the C++11 standard, we know that move constructor is used for temporary right value in normal. So the move constructor throwing exception is such a dangerous thing, and we can declare "noexcept" for the move constructor to avoid it.

Using move_if_noexcept(), although it loss in performance, but can make the process safe. And the function will activate the move constructor when move constructor is declared "noexcept".

(Sorry for my poor English.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!