C++ 通过引用返回

标签 c++ reference

比如,我有一个返回引用的函数,我想确保调用者只将它作为引用获取,而不应将其作为拷贝接收。 这在 C++ 中可能吗?

为了更清楚。我有这样的类(class)。

class A
{
private:
    std::vector<int>  m_value;
    A(A& a){ m_value = a.m_value; }

public:
    A() {}
    std::vector<int>& get_value() { return m_value; }
};

int main()
{
    A a;
    std::vector<int> x = a.get_value();
    x.push_back(-1);
    std::vector<int>& y = a.get_value();
    std::cout << y.size();

    return 0;
}

谢谢, 悟空。

最佳答案

您可以通过使类不可复制来为自己的类做您想做的事。

您可以通过将复制构造函数和 operator= 作为私有(private)或 protected 成员来使类不可复制。

class C
{
private:
  C(const C& other); 
  const C& operator=(const C&);

};

有一个制作 NonCopyable class 的好例子在这里你可以从中派生出你自己的类型。

如果您正在使用 boost,您还可以使用 boost::noncopyable .

替代方案:

另一种解决方案是使用 void 返回类型并让调用者通过引用传递他们的变量。这样,当您获得对调用者对象的引用时,不会进行任何复制。

关于C++ 通过引用返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2580729/

相关文章:

c++ - 除了 boost::pool 之外,C++ 中的自定义池分配器

c++ - 构建项目时 Unresolved external symbol 错误

c++ - 无法为编译 SFML 项目创建 cmake 规则

c - 函数引用返回的变量给出了奇怪的值

com - TFS Build服务器和COM引用-起作用吗?

c++ - 获取相对于指定条目路径的递归迭代目录的路径

c++ - std::bind 与来自父类的重载函数

c++ - 将 const 引用传递给原始类型有什么用?

c++ - 正确返回 vector 引用

c# - 在 C# 中引用主线程