为什么不调用移动构造函数?

时间:2014-01-07 09:13:33

标签: c++ c++11 stl constructor move-constructor

我正在使用 C ++ Primer 5th Edition 进行练习,如下所示:

  

练习13.50:将打印语句放入你的移动操作中   字符串类并从第13.6.1节(第13页)中的练习13.48重新运行该程序。   534)使用向量来查看何时避免复制。(P.544)

String是一个练习课程,其行为类似于std::string而不使用任何模板。 String.h文件:

class String
{
public:
    //! default constructor
    String();

    //! constructor taking C-style string i.e. a char array terminated with'\0'.
    explicit String(const char * const c);

    //! copy constructor
    explicit String(const String& s);

    //! move constructor    
    String(String&& s) noexcept;

    //! operator =
    String& operator = (const String& rhs);

    //! move operator =     
    String& operator = (String&& rhs) noexcept;

    //! destructor
    ~String();

    //! members
    char* begin() const  { return elements;   }
    char* end()   const  { return first_free; }

    std::size_t size()     const {return first_free - elements;  }
    std::size_t capacity() const {return cap - elements;         }

private:

    //! data members
    char* elements;
    char* first_free;
    char* cap;

    std::allocator<char> alloc;

    //! utillities for big 3
    void free();

};

String.cpp的默认,复制和移动构造函数的实现:

//! default constructor
String::String():
    elements    (nullptr),
    first_free  (nullptr),
    cap         (nullptr)
{}

//! copy constructor
String::String(const String &s)
{
    char* newData = alloc.allocate(s.size());
    std::uninitialized_copy(s.begin(), s.end(), newData);

    elements = newData;
    cap = first_free = newData + s.size();

    std::cout << "Copy constructing......\n";
}

//! move constructor    
String::String(String &&s) noexcept :
    elements(s.elements), first_free(s.first_free), cap(s.cap)
{
    s.elements = s.first_free = s.cap = nullptr;
    std::cout << "Move constructing......\n";
}

Main.cpp

int main()
{
    std::vector<String> v;
    String s;
    for (unsigned i = 0; i != 4; ++i)
        v.push_back(s);

    return 0;
}

输出:

Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......
Copy constructing......

可以看出,移动构造函数根本没有被调用。当向量分配更多内存时,为什么不调用移动构造函数?

更新

编译器的信息:

gcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1) 
带有打印容量及其输出的

main.cpp

int main()
{
    std::vector<String> v;
    String s;
    for (unsigned i = 0; i != 4; ++i)
    {
        std::cout << v.capacity() << "\n";
        v.push_back(s);
    }

    return 0;
}

输出:

0
Copy constructing......
1
Copy constructing......
Copy constructing......
2
Copy constructing......
Copy constructing......
Copy constructing......
4
Copy constructing......

1 个答案:

答案 0 :(得分:1)

我在MinGW上用gcc 4.7.1重现...

添加~String() noexcept解决了问题...