Ign*_*kas 5 c++ argument-passing
这是一个非常基本的问题,但是,从C++专家那里听到它会很好.
在C++中有两种相似的方法来声明by-reference参数.
1)使用"星号":
void DoOne(std::wstring* iData);
Run Code Online (Sandbox Code Playgroud)
2)使用"&"":
void DoTwo(std::wstring& iData);
Run Code Online (Sandbox Code Playgroud)
每种方法的含义是什么?在任何情况下都有任何问题吗?
奖金#1:在#1和#2中调用方法的正式方法是什么?它们都被称为"按参考"吗?
奖金#2:故意使用std :: wstring.在每种情况下,对标准库类有什么影响?
#1使用指针参数('将指针传递给'),#2使用参考参数('通过引用传递').它们非常相似,但请注意,调用代码在两种情况下看起来不同:
std::wstring s;
DoOne(&s); // pass a pointer to s
DoTwo(s); // pass s by reference
Run Code Online (Sandbox Code Playgroud)
有些人更喜欢#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
}
Run Code Online (Sandbox Code Playgroud)