firebush firebush - 1 month ago 7
C++ Question

Value replacement without using the assignment operator

Consider this minimal example:

#include <iostream>

using namespace std;

class A
{
public:
A() { cout << "Making A" << endl; }
A& operator=(const A& other) = delete;
};


int
main(int argc, char* argv[])
{
A a;
a = A();

return 0;
}


Compiling gives the following error:

$ g++ -std=c++11 -Wall test.cc -o test && ./test
test.cc: In function ‘int main(int, char**)’:
test.cc:17:7: error: use of deleted function ‘A& A::operator=(const A&)’
a = A();
^
test.cc:9:8: error: declared here
A& operator=(const A& other) = delete;
^


I want to "reset" the value of
a
to a newly constructed
A
. Is there a way for me to do this by only using the constructor? That is, without using the assignment operator which needs to be deleted in my real-world code? I tried, for instance, using
std::move
a la
a = std::move(A());
, but that gives the same error.

Answer

You can only call the constructor for an object once. After that, the object is already constructed, and cannot be constructed a second time.

You can destroy the object and reconstruct it in place:

a.~A();
::new (&a) A();

If you find yourself needing to do this often, it's better to just provide a .clear() member or something similar... or maybe just not delete the assignment operator. You haven't provided enough detail.