What are the differences between parameter definitions like (type & name) and (type * name)?

A very simple question, but, nevertheless, it would be nice to hear from a C ++ guru.

There are two pretty similar ways of declaring byte parameters in C ++.

1) Using an asterisk:

void DoOne(std::wstring* iData);

2) Using the "ampersand":

void DoTwo(std::wstring& iData);

What are the implications of each method? Is there any question anyway?

Bonus # 1: What will be the formal way to call the method in # 1 and # 2? Are they both called "by-reference"?

Bonus # 2: std :: wstring is used deliberately. What will matter for standard library classes in each case?

+5
source share
7 answers

# 1 ( " " ), # 2 ( " " ). , , - :

std::wstring s;

DoOne(&s); // pass a pointer to s
DoTwo(s); // pass s by reference

# 1, , , s ( ). ( ) # 2, NULL.

const. const:

void ByConstPointer(const std::wstring&);
void ByConstReference(const std::wstring*);

void test()
{
  ByConstPointer(&std::wstring(L"Hello")); // error: cannot take address of temporary
  ByConstReference(std::wstring(L"Hello")); // fine
}
+5

: NULL , , .

, ( !) - NULL, NULL.

+2

. - , ?

: . , - . , .

:

{
    std::wstring data;
    DoOne(&data);
    DoTwo(data);
}

, , , . , , .

{
    std::wstring* pData = new std::wstring();
    DoOne(pData);
    DoTwo(*pData);
}

, pData NULL, DoTwo, DoOne NULL .

+1

++ gure ( CV), ; (.. null), .

, , , - , .

0

DoOne iData NULL. DoOne, .

-

void DoOne(std::wstring* iData)
{
   //Use iData
   delete iData;
   iData = NULL;
}

{
    std::wstring* pData = new std::wstring();
    DoOne(pData);
    pData->someFunction(); //Crash
}
0

, :

: . , .

connsider:

void f( int * p1 ) {
   int ** p2 = & p1;
}

p1 " " - , .

void f( int & r ) }
   int * p = & r;
}

r , . , r.

NULL . NULL undefined - .

0

If you write a function that receives a variable with a pointer, you will most likely have to check if the pointer is valid (for example, not NULL), otherwise you risk a program crash.

0
source

All Articles