gpt4 book ai didi

C++11: 'decltype class instance declaration' with std::move( ) 不调用 'move constructor.' 为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:12 24 4
gpt4 key购买 nike

我最近开始使用 c++ 并且我选择学习 c++11 特性。但 C++ 代码如何运行有时并不是那么有形。

下面是我的代码。在 decltype(std::move(sample)) sample2 = std::move(sample); 部分,我不确定为什么这一行不调用 move 构造函数。你能解释一下为什么吗?

#include <iostream>

class AAA
{
public:
AAA() { std::cout << "default constructor" << std::endl; }
AAA(const AAA& cs) { std::cout << "copy constructor" << std::endl; }
AAA(AAA&& cs) { std::cout << "move constructor" << std::endl; }
~AAA() { std::cout << "destructor" << std::endl; }
};

int main(int argc, char* args[])
{
AAA sample;
// ((right here))
decltype(std::move(sample)) sample2 = std::move(sample);
return 0;
}

它是在 [ubuntu 16.04 LTS] 和 [gcc 5.4.0] 上编译的

原码:https://ide.geeksforgeeks.org/tALvLuSNbN

最佳答案

函数std::move<T>返回 T && , 所以对于 std::move(sample)它返回 AAA && .这是 rvalue reference并且表现得很像 lvalue reference (像 AAA & 这样的类型将是一个左值引用)因为它们都是已经存在的对象的别名。

了解 std::move 很重要不会本身会导致任何东西被 move 。它只是返回一个右值引用给它的参数。例如std::move(foo);一个人绝对什么都不做。只有当结果用于初始化或分配给对象时,它才有用。

例如auto bar = std::move(foo);将返回对 foo 的右值引用并使用该引用来调用 bar的构造函数。

回答这个问题,因为std::move(sample)返回 AAA && , 有问题的行与 AAA && sample2 = std::move(sample); 相同.该行为实际上与 AAA & sample2 = sample; 相同.在这两种情况下,您都在初始化对现有对象的引用,并且不需要构造新对象。

如果你的目标是 move sample进入一个新的AAA , 正确的行是 auto sample2 = std::move(sample);就像你用 sample3 做的一样.尽管要注意 sample3 行正在从一个已经搬离的 sample 搬迁.

关于C++11: 'decltype class instance declaration' with std::move( ) 不调用 'move constructor.' 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51365053/

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