gpt4 book ai didi

c++ - 为什么流插入重载中的右操作数必须是引用?

转载 作者:太空狗 更新时间:2023-10-29 20:51:44 25 4
gpt4 key购买 nike

对于C++的插入重载,我们通常这样做:

ostream& operator<<(ostream& os, X& object){
// operation
return os;
}

我的问题是:为什么它必须引用 X 类型的变量对象?

最佳答案

My question here is: why it has to take a reference to the variable object of type X?

你不需要引用,它不是强制性的。在任何情况下,请考虑到这一点,因为您不打算修改对象,所以最好写成:

ostream& operator<<(ostream& os, const X& object){
// operation
return os;
}

简单的替代方法是按值传递对象,方法是:

ostream& operator<<(ostream& os, X object){
// operation
return os;
}

问题出在哪里?您的程序将继续运行,但其性能会受到影响。将指针传递给对象(最终是引用)不如复制整个对象有效。假设 X 具有以下实现,即它实际上是 GpsTrack 类:

/** A complete track, composed by GpsPoints. */
class GpsTrack {
public:
/** Creates a new, empty track. */
GpsTrack()
{}

/** Adds a new point to the track.
* @param p The new point.
*/
void add(const GpsPoint &p)
{ gpsPoints.push_back( p ); }

/** @return The point at position i. */
const GpsPoint &operator[](int i)
{ return gpsPoints[ i ]; }

/** @return The number of points in the track. */
int size() const
{ return gpsPoints.size(); }

/** @return A textual representation of the track. */
std::string toString() const;

/** Adds support for the << operator. */
friend std::ostream& operator<<(std::ostream& os, const GpsTrack& track)
{ os << track.toString(); return os; }
private:
std::vector<GpsPoint> gpsPoints;
};

为了示例,让我们以 32 位机器为例。每个 GpsPoint 包含一对 double的,每个存储 8 个字节,所以总共 16 个字节。如果 GpsTrack 包含 5000 个点,则结果约为 78KB。这通过 std::vector 透明地存储在堆中.

也就是说,我们对 operator<<() 有以下实现,而不是上面给出的实现.

    /** Adds support for the << operator. */
friend std::ostream& operator<<(std::ostream& os, GpsTrack track)
{ os << track.toString(); return os; }

然后,为了让 trackoperator<<() 内工作, C++ 将复制对象。 std::vector gpsPoints 将被透明地复制到另一个 vector 中,在堆中复制其信息(在方法开始时分配并在方法结束时释放)。但是,此信息由 GpsPoint 组成,在最坏的情况下(取决于其实现),这将意味着遍历所有点并调用它们的复制构造函数。这不仅是在浪费时间,也是在浪费资源(即内存)。

您可以将其作为 const 引用传递,它与指针一样高效,与按值传递一样安全(不允许修改)。

希望这对您有所帮助。

关于c++ - 为什么流插入重载中的右操作数必须是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48658227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com