mercredi 29 avril 2020

How to force std::vector to use move constructor instead of the copy one?

I want to use move semantics in my application, not to copy the data. Here is the code:

using namespace std;

struct TestData
{
    TestData(const TestData&) = delete;
    TestData& operator=(const TestData&) = delete;
    TestData(TestData &&other) = default;
    TestData& operator=(TestData &&other) = default;

    TestData() { std::cout << "TestData()" << std::endl; }
    ~TestData() noexcept {
        if(ptr != null) delete []ptr;
        std::cout << "~TestData(), ptr = " << (ptr == nullptr ? "nullptr" : "not null") << std::endl; 
    }
    int x;
    char *ptr = nullptr;
};

void add(std::vector<TestData> &vector)
{
    TestData d;
    d.x = 1;
    d.ptr = new char[12];
    memcpy(d.ptr, "Test string", 11);
    vector.push_back(d);
}


int main()
{
    std::vector<TestData> v;
    add(v);
    add(v);

    return 0;
}

But the GCC compiler fails with the error:

error: use of deleted function ‘TestData::TestData(const TestData&)’

But I don't want to copy the data, I want to move that. The reason is that copying data cause to copy the pointer (ptr) and so attempt to delete it in the destructor cause to double free corruption.

So the question - how to force that GCC will use move constructor?

  • GCC v. 9.3.0
  • Ubuntu 20.04

Aucun commentaire:

Enregistrer un commentaire