C++中的双重和移动功能
double & and move function in C++
我想在c++中使用参数来存储任何值/对象。在这个示例中,我尝试存储来自全局变量的值,作为一个简化的示例。
这个代码不工作,
int value = 20;
void returnPointer2(int* hello)
{
hello = &value;
}
// It changes nothing
int value2 = 100;
returnPointer2(&value2);
cout << value2 << endl;
因为我需要双指针。
void returnPointer3(int** hello)
{
*hello = &value;
}
int* vp2 = new int();
*vp2 = -30;
returnPointer3(&vp2);
cout << *vp2 << endl; // expects 20
我提醒了引用,我可以使用指针引用来获得相同的结果。
void returnPointer4(int* & hello)
{
cout << "value : " << value;
hello = &value;
}
int* vp3 = new int();
*vp3 = -130;
returnPointer4(vp3); // also expects 20, but much simpler to use
cout << "better : " << *vp3 << endl;
我尝试了双引号&,它可以编译。
void returnPointer5(int&& hello)
{
cout << "value : " << value;
hello = value;
}
但是,如果输入的是整型变量,则不能编译
int vp4 = 123;
returnPointer5(vp4); // also expects 20, but even more simpler to use
cout << "best : " << vp4 << endl;
这是一个错误消息。
pointer_return.cpp:31:6: error: initializing argument 1 of 'void returnPointer5(int&&)'
void returnPointer5(int&& hello)
我碰巧知道move
,它可以用这个代码工作。
int vp4 = 123;
returnPointer5(move(vp4)); // also expects 20, but much simpler to see
cout << "best : " << vp4 << endl;
这个move
函数背后的魔法/逻辑是什么?
这里有很多东西混合在一起,但为了保持简单,我将解决您的根本问题。
&&
与**
完全不同。
&&
是右值引用,而**
是指向指针的指针。
作为第二点,你在你的函数名中声明你想做什么:returnPointer4
.
你想要返回一个指向整型的指针。int*&
是指针引用的正确语法。
再看一遍你的问题,为什么不用下面的句子呢?
int& returnGlobalReference() {
return value;
}
然后在你的其他函数中:
int& value2 = returnGlobalReference();
第一次尝试犯了按值传递指针的典型错误,修改了它在函数中的地址,并期望它指向的对象发生变化。
正如评论中提到的,
void returnPointer2(int* hello)
{
hello = &value; // don't do this, it only modifies what the
// pointer hello, which resides in the stack, points to
*hello = value; // do this instead. even though hello still resides in the
// stack, you're modifying the location that hello points to,
// which was your original intention
}
为什么要传递指针呢?当您调用函数时,静态变量是否不可用?(也许,不同的文件?)
std::move的神奇之处在于:
std::move的实际声明要复杂一些,但本质上,它只是将static_cast转换为右值引用。
从这里取。
正如Jeffery Thomas已经说过的,&&
不是对引用的引用,而是对右值的引用。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- C++ - 没有自定义交换功能的移动分配运算符?
- 具有文本角色扮演功能的移动系统
- 传递具有移动捕获功能的 lambda
- 在鼠标按下时移动 SDL2 窗口的功能闪烁窗口并且移动速度不够快
- 编译器生成的移动成员在静态数据成员上功能
- 将功能移动到其他文件
- 为了支持移动语义,应通过unique_ptr,值或rvalue获取功能参数
- 如果将功能的非常简单的定义移动到.cpp,则编译时间的减少是多少
- 如何转移qpainter?(从出厂功能中移动对象)
- 是否可以实现std ::移动和清除功能
- QProgresDialog:忙碌的等待栏在功能执行时没有移动
- Qt移动插槽功能到另一个cpp文件
- 移动功能体,避免完全克隆
- 我不能在不使用指针的情况下返回 2d 数组!我正在制作一个井字游戏类型游戏,这是我的向上移动功能
- 使用Qt插件将功能移动到VS2010中的其他文件时出现链接器错误
- C++中的双重和移动功能
- Qt:鼠标移动功能不正常
- 如何使用 ASM 将 FARPROC 的内存地址移动到另一个功能?