vendredi 21 octobre 2022

Declaring a variable and assigning with move assignment operator in one statement on Clang causes seg fault

I've got this trivial example of what I thought was calling the move assignment operator of this Test struct. Running it, it calls the move constructor and then seg faults on destruction on Clang. On MSVC, it works fine.

I'm a bit confused by that behavior cause i would expect it to construct with the parameterless constructor and then call the move assignment operator.

#include <iostream>

struct Test
{
Test() : data(nullptr), dataCount(0) {}

Test(Test&& other)
{
  std::cout << "mv cstr" << std::endl << std::flush;
  delete[] data;
  data = other.data;
  other.data = nullptr;

  dataCount = other.dataCount;
}

Test& operator=(Test&& other)
{
  std::cout << "mv op" << std::endl << std::flush;
  
  delete[] data;
  data = other.data;
  other.data = nullptr;

  dataCount = other.dataCount;
  return *this;
}

~Test()
{
  std::cout << "dstr " << (void*)this << std::endl << std::flush; 
  delete[] data;
  data = nullptr;
}

char* data;
size_t dataCount;
};

int main() {
    Test test;
    test.data = new char[3];
    test.dataCount = 3;

    Test newTest = std::move(test);
    return 0;
}

If I instead declare and then assign, it of course works as expected

int main() {
    Test test;
    test.data = new char[3];
    test.dataCount = 3;

    Test newTest;
    newTest = std::move(test);
    return 0;
}

I've read through the std::move, move assignment operator, and move constructor documentation a few times but I'm just not getting what's specifically different here or left up to the compilers that would give different behavior between MSVC and Clang.

What am I missing?

Aucun commentaire:

Enregistrer un commentaire