根据答案/sf/answers/828970971/,如果你这样编码,函数参数Bubble * targetBubble将被复制到函数内部。
bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
targetBubble = bubbles[i];
}
Run Code Online (Sandbox Code Playgroud)
然而,我做了一个测试,发现作为函数参数的指针将与外部的相同,直到我更改它的值:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
输出如下:
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
Run Code Online (Sandbox Code Playgroud)
所以,事实是,作为函数参数的指针不会被复制,直到它被更改,对吗?或者我在这里遗漏了什么?
指针(仅保存地址的变量 - 通常只是 32 或 64 位整数)被复制。指针指向的不是。
所以是的,你错过了一些东西。您需要了解指针并不是它指向的对象。它只是一个小整数值,表示“那是那边的对象”——复制该指针很便宜,并且不会改变它所指向的内容。