firebush firebush - 9 months ago 40
C++ Question

Value replacement without using the assignment operator

Consider this minimal example:

#include <iostream>

using namespace std;

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

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

return 0;

Compiling gives the following error:

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

I want to "reset" the value of
to a newly constructed
. 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
a la
a = std::move(A());
, but that gives the same error.

Answer Source

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:

::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.