根據回答https://stackoverflow.com/a/11842442/5835947,如果你這樣編碼,功能參數Bubble * targetBubble
將被複制到函數內部。C++:作爲函數參數的指針是否真的被複制?
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
所以,事實是,作爲函數參數的指針將不會被複制,直到它被更改,對吧?或者我在這裏錯過了什麼?
你在說「*指針的地址是*」,但是你正在打印指針的值。是的,C++具有「按值傳遞」的語義,所以指針和所有函數參數都被複制,除非它們是引用。 – juanchopanza
郵寄包裹時,請在上面放上地址標籤。包裹然後移動,直到它到達目的地。作爲地址標籤的物理紙張的位置始終在變化,但其上的信息保持不變。 –
我投票結束這個問題作爲題外話,因爲它基於一個簡單的誤解是什麼符合一個_pointer value_和_value保存在指針的地址。 –