Returning an object in C++

前端 未结 5 919
一整个雨季
一整个雨季 2021-02-14 12:02

I am learning C++ from a background of mostly C and Java and I am curious on what is the best way to return an object in C++ without having to copy the object. From my understa

5条回答
  •  囚心锁ツ
    2021-02-14 12:36

    Often you can avoid copies by returning a const reference to a member variable. For example:

    class Circle {
        Point center;
        float radius;
    public:
        const Point & getCenter() const { return center; };
    };
    

    This is equivalent to return ¢er in execution and in fact will likely be inlined simply resulting in direct (read-only) access of the member from the caller.

    In cases where you construct a temporary to return the compiler may elide the extra copy as an optimization, requiring no special syntax on your part.

提交回复
热议问题