gpt4 book ai didi

c++ - 为什么从初始化列表中初始化 vector 时不使用 move 构造(通过隐式构造函数)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:50 27 4
gpt4 key购买 nike

为了演示 move 语义,我编写了以下示例代码,其中包含来自 int 的隐式构造函数。

struct C {
int i_=0;
C() {}
C(int i) : i_( i ) {}
C( const C& other) :i_(other.i_) {
std::cout << "A copy construction was made." << i_<<std::endl;
}
C& operator=( const C& other) {
i_= other.i_ ;
std::cout << "A copy assign was made."<< i_<<std::endl;
return *this;
}
C( C&& other ) noexcept :i_( std::move(other.i_)) {
std::cout << "A move construction was made." << i_ << std::endl;
}
C& operator=( C&& other ) noexcept {
i_ = std::move(other.i_);
std::cout << "A move assign was made." << i_ << std::endl;
return *this;
}
};

auto vec2 = std::vector<C>{1,2,3,4,5};
cout << "reversing\n";
std::reverse(vec2.begin(),vec2.end());

有输出

A copy construction was made.1
A copy construction was made.2
A copy construction was made.3
A copy construction was made.4
A copy construction was made.5
reversing
A move construction was made.1
A move assign was made.5
A move assign was made.1
A move construction was made.2
A move assign was made.4
A move assign was made.2

现在,反向显示了 2 次交换(每次使用一次 move 赋值和两次 move 构造),但为什么从初始化列表创建的临时 C 对象不可能从中 move ?我以为我有一个整数的初始化列表,但我现在想知道我之间是否有一个 Cs 的初始化列表,不能从中 move (作为它的常量)。这是正确的解释吗? - 发生了什么事?

Live demo

最佳答案

I thought I had an initializer list of integers, but I'm now wondering if what I have in between is an initializer list of Cs, which can't be moved from (as its const). Is this a correct interpretation?

这是正确的。 vector<C>没有 initializer_list<int>构造函数甚至 initializer_list<T>一些模板参数的构造函数 T .它确实有一个 initializer_list<C>构造函数 - 它由您传入的所有整数组成。自 initializer_list 的支持以来是一个 const 数组,你得到一堆拷贝而不是一堆 move 。

关于c++ - 为什么从初始化列表中初始化 vector 时不使用 move 构造(通过隐式构造函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com