C ++如何获取返回引用并将refence保存为函数中的局部变量?

时间:2021-07-30 22:56:03

I have a function inside a class that returns a reference to a member variable.

我在类中有一个函数,它返回对成员变量的引用。

std::vector<uint8> & getBuffer() const
{
   return m_myBuffer;
}

Now say in another class I call this method:

现在在另一个类中说我称之为这个方法:

int someFunction()
{
   std::vector<uint8> myFileBuffer = myFile.getBuffer();
}

This line calls the copy constructor of vector and makes me a local buffer. I do not want this, how can I instead set myFileBuffer to reference the myFile.getBuffer().

这一行调用vector的复制构造函数,使我成为一个本地缓冲区。我不想要这个,我怎样才能设置myFileBuffer来引用myFile.getBuffer()。

I know I can do this via pointers but wanted to use references if it is possible.

我知道我可以通过指针做到这一点但是如果可能的话想要使用引用。

Thanks.

2 个解决方案

#1


Note since your member method is const you should be returning a const reference.

注意,因为你的成员方法是const,你应该返回一个const引用。

// Note the extra const on this line.
std::vector<uint8> const& getBuffer() const
{
    return m_myBuffer;
}

So to use the returned value by reference do this:

因此,通过引用使用返回的值,请执行以下操作:

std::vector<uint8> const& myFileBuffer = myFile.getBuffer();

#2


Declare your local variable as being a reference type instead of a value type, i.e. like this ...

将您的局部变量声明为引用类型而不是值类型,即像这样......

std::vector<uint8>& myFileBuffer = myFile.getBuffer();

... instead of like this ...

......而不是像这样......

std::vector<uint8> myFileBuffer = myFile.getBuffer();

#1


Note since your member method is const you should be returning a const reference.

注意,因为你的成员方法是const,你应该返回一个const引用。

// Note the extra const on this line.
std::vector<uint8> const& getBuffer() const
{
    return m_myBuffer;
}

So to use the returned value by reference do this:

因此,通过引用使用返回的值,请执行以下操作:

std::vector<uint8> const& myFileBuffer = myFile.getBuffer();

#2


Declare your local variable as being a reference type instead of a value type, i.e. like this ...

将您的局部变量声明为引用类型而不是值类型,即像这样......

std::vector<uint8>& myFileBuffer = myFile.getBuffer();

... instead of like this ...

......而不是像这样......

std::vector<uint8> myFileBuffer = myFile.getBuffer();