C++中的双重和移动功能

double & and move function in C++

本文关键字:移动 功能 C++      更新时间:2023-10-16

我想在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已经说过的,&&不是对引用的引用,而是对右值的引用。