为什么复制构造函数在这里调用?

时间:2017-09-11 08:24:21

标签: c++ constructor copy-constructor

我有以下代码:

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;

2 个答案:

答案 0 :(得分:7)

s值副本friend String operator+(String lhs, const String& rhs)占用,主要是因为s不是匿名临时的,因此不适合移动构建。获取该值复制需要复制构造函数。

答案 1 :(得分:0)

根据我的理解,调用复制构造函数来接收+运算符的返回值。