我今天有以下代码:
std::vector<float>& vecHighRes = highRes->getSamples();
PMHighResolution.cpp / .h
std::vector<float>& getSamples();
static std::vector<float> fSamples;
std::vector<float>& PMHighResolution::getSamples()
{
return fSamples;
}
Run Code Online (Sandbox Code Playgroud)
为什么我需要两次?在我假设的返回中,因为它否则会生成要返回的向量的副本,但为什么我需要在assign运算符中使用它(
std::vector<float>& vecHighRes = highRes->getSamples();
)?
的&在LHS意味着vecHighRes是一个参考:
std::vector<float>& vecHighRes = highRes->getSamples();
Run Code Online (Sandbox Code Playgroud)
如果你省略了&,那vecHighRes将是vector的副本fSamples,由返回的引用构造getSamples.
它与此相同:
int a = 42;
int& b = a; // b is a reference to a
int c = b; // c is a copy of a
Run Code Online (Sandbox Code Playgroud)