C++:指针作为函数的参数真的被复制了吗?

cld4siwp  于 2023-04-01  发布在  其他
关注(0)|答案(2)|浏览(176)

根据答案https://stackoverflow.com/a/11842442/5835947,如果你这样编码,函数参数Bubble * targetBubble将被复制到函数内部。

bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
    targetBubble = bubbles[i];
}

然而,我做了一个测试,发现作为函数参数的指针将与外部的指针相同,直到我改变了它的值:

// c++ test ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "c++ test ConsoleApplication2.h"
using namespace std;
#include<iostream>



int main()
{
    int a= 1;
    int* pointerOfA = &a;

    cout << "address of pointer is" << pointerOfA << endl;
    cout << *pointerOfA << endl;
    func(pointerOfA);
    cout << *pointerOfA << endl;



}

void func(int *pointer)
{
    cout << "address of pointer is " << pointer  <<" it's the same as the pointer outside!"<<endl;

    int b = 2;
    pointer = &b;
    cout << "address of pointer is" << pointer <<" it's changed!"<< endl;

    cout << *pointer<<endl;

}

输出如下:

address of pointer is0093FEB4
1
address of pointer is 0093FEB4 it's the same as the pointer outside!
address of pointer is0093FDC4 it's changed!
2
1

所以,事实是,指针作为函数参数是不会被复制的,除非它被改变了,对吗?,或者我错过了什么?

klsxnrf1

klsxnrf11#

  • 指针 *(变量只包含一个地址-通常只是一个32或64位的整数)被复制。指针 * 指向的 * 不是。

所以,是的,你遗漏了一些东西。你需要明白指针不是它所指向的对象。它只是一个小整数值,表示“那是对象”-复制那个指针很便宜,并且不会改变它所指向的对象。

vuktfyat

vuktfyat2#

指针的使用是因为它不会复制整个对象,因为复制的代价可能很高,它会将对象的地址作为参数复制/传递给函数。当你将指针传递给函数并在函数外部或函数中对其进行更改时,它会修改同一个对象。你可以通过执行*p来打印指针对象的值。如果你想检查指针变量是否被复制,那么输出p并检查哪个可能不同。

相关问题