作为 (type& name) 和 (type* name) 的参数定义之间有什么区别? [英] What are the differences between parameter definitions as (type& name), and (type* name)?
问题描述
一个非常基本的问题,但仍然很高兴听到 C++ 专家的意见.
A very basic question, but still, it would be good to hear from C++ gurus out there.
在 C++ 中有两种相当相似的方法来声明按引用参数.
There are two rather similar ways to declare by-reference parameters in C++.
1) 使用星号":
void DoOne(std::wstring* iData);
2) 使用&":
void DoTwo(std::wstring& iData);
每种方法的含义是什么?有什么问题吗?
What are implications of each method? Are there any gotcha's in any case?
奖励#1:在#1 和#2 中调用方法的正式方式是什么?它们都被称为按引用"吗?
Bonus #1: What would be a formal way to call method in #1 and #2? Are they both called "by-reference"?
奖励 #2:故意使用 std::wstring.在每种情况下对标准库类有什么影响?
Bonus #2: std::wstring is used deliberately. What would be implications towards standard library classes in each case?
推荐答案
#1 使用指针参数('passing a pointer to'),#2 使用引用参数('passing by reference').它们非常相似,但请注意,两种情况下的调用代码看起来不同:
#1 uses a pointer parameter ('passing a pointer to'), #2 uses a reference parameter ('passing by reference'). They are very similar, but note that the calling code looks different in the two cases:
std::wstring s;
DoOne(&s); // pass a pointer to s
DoTwo(s); // pass s by reference
有些人更喜欢#1,使用通过指针传递的约定表示函数可能会更改 s 的值(即使任何一个函数都可以).其他人(包括我自己)更喜欢 #2,因为通过引用传递不允许传递 NULL.
Some people prefer #1, using a convention that passing by pointer indicates that the function might change the value of s (even though either function could). Other people (myself included) prefer #2, since passing by reference does not allow NULL to be passed.
传递const
指针或引用时还有一个重要的区别.临时变量只能传递给 const 引用参数:
There is another important difference when passing by const
pointer or reference. A temporary variable can only be passed to a const reference parameter:
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
}
这篇关于作为 (type& name) 和 (type* name) 的参数定义之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!