2017-06-04 68 views
0

根據回答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 

所以,事實是,作爲函數參數的指針將不會被複制,直到它被更改,對吧?或者我在這裏錯過了什麼?

+2

你在說「*指針的地址是*」,但是你正在打印指針的值。是的,C++具有「按值傳遞」的語義,所以指針和所有函數參數都被複制,除非它們是引用。 – juanchopanza

+0

郵寄包裹時,請在上面放上地址標籤。包裹然後移動,直到它到達目的地。作爲地址標籤的物理紙張的位置始終在變化,但其上的信息保持不變。 –

+0

我投票結束這個問題作爲題外話,因爲它基於一個簡單的誤解是什麼符合一個_pointer value_和_value保存在指針的地址。 –

回答

2

指針(變量只保存一個地址 - 通常只是一個32或64位整數)被複制。 什麼指針指向不是。

所以是的,你缺少的東西。你需要明白指針是而不是它指向的對象。它只是一個小整數值,表示「這是,在那裏」 - 並且複製那個指針很便宜,並且不會改變它指向的內容。

0

使用了指針,因爲不是複製整個對象,而是複製昂貴的對象,它會將/ psas複製到對象的地址作爲參數。當您將指針傳遞給函數並在函數之外或在函數中對其進行更改時,它將修改相同的對象。您正在通過執行*p來打印指示對象的值。如果你想檢查指針變量是否被複制,那麼輸出p並檢查哪一個可能不同。