C++:除了在函数中使用引用变量之外,还有其他原因吗?

问题描述 投票:0回答:1

据我所知,除非

  • A) 涉及一个返回引用或接受引用的函数,或者
  • B) 涉及一个类,

没有真正的理由使用它。我认为使用指针或原始变量都不能更好地实现它们的目的。

c++
1个回答
0
投票

考虑以下简单的程序。在

A b
情况下,构造函数被调用。在第二
A c = b;
行中,调用复制构造函数。在最后一种情况下,根本不会发生复制或移动。

这是否有益取决于复制操作的成本有多大。显然,对于这个简单的示例来说,这并不重要,但想象一下您的类/结构分配了大量内存,然后在副本上必须将所有状态复制到新对象。这可能会严重影响性能和扩展。分配给引用不会产生这种影响。

#include <iostream>

using std::cout;

struct A {
    A() { cout << "Constructor\n"; }
    ~A() { cout << "Destructor\n"; }
    A(const A& a) { cout << "Copy constructor\n"; }
    A(A&& a) { cout << "Move constructor\n"; }
    A& operator=(const A& a) { cout << "Copy assignment\n"; return *this; }
    A& operator=(A&& a) { cout << "Move assignment\n"; return *this; }
};

int main() {
    A b;
    A c = b;
    A& d = b;
}

建议阅读:三/五/零规则

© www.soinside.com 2019 - 2024. All rights reserved.