为什么在此处调用复制构造函数

Why is copy constructor called here?

本文关键字:复制 构造函数 调用 为什么      更新时间:2023-10-16

我有以下代码:

template<class T = char>
class String
{
public:
    // Default constructor
    String()
        : buffer(nullptr),
        len(0)
    {
        cout << "Default constructor" << endl;
    }
    // Constructor
    String(const char* s)
    {
        cout << "Constructor (const char*)" << endl;
        //...
    }
    // Virtual destructor.
    virtual ~String()
    {
        cout << "Destructor" << endl;
        len = 0;
        delete[] buffer;
    }

    // Copy constructor
    String(const String& s)
    {
        cout << "Copy constructor" << endl;
        buffer = new T[s.len];
        std::copy(s.buffer, s.buffer + s.len, buffer);
        len = s.len;
    }

    // Copy assignment operator (uses copy and swap idiom)
    String& operator=(String s)
    {
        cout << "Copy assignment operator (copy and swap idiom)" << endl;
        std::swap(buffer, s.buffer);
        return *this;
    }

    // Move constructor
    String(String&& s)
    {
        cout << "Move constructor" << endl;
    }

    // compound assignment (does not need to be a member,
    // but often is, to modify the private members)
    String& operator+=(const String& rhs)                            
    {                          
        cout << "operator+=" << endl;       
        //...
        return *this; // return the result by reference
    }
    // friends defined inside class body are inline and are hidden from non-ADL lookup
    // passing lhs by value helps optimize chained a + b + c
    // otherwise, both parameters may be const references
    friend String operator+(String lhs, const String& rhs)
    {
        cout << "operator+" << endl;
        lhs += rhs; // reuse compound assignment
        return lhs; // return the result by value (uses move constructor)
    }

private:
    T* buffer;
    size_t len;
};

int main()
{
    String<> s("Hello ");
    String<> s2("World");
    // call copy constructor first?
    String<> s3 = s + s2;
    return 0;
}

,输出为:

Constructor (const char*)
Constructor (const char*)
Copy constructor
operator+
operator+=
Move constructor
Destructor

我的问题是,为什么要立即调用复制构造函数:

String<> s3 = s + s2;

a s的值复制是由friend String operator+(String lhs, const String& rhs)采取的,从本质上讲,因为s不是匿名的临时性,因此也不是移动构造的合适候选者。取值副本需要复制构造函数。

对我的理解,复制构造函数被调用以接收+操作员的返回值。