Is it possible to declare operator = private and synthesize it by the compiler simultaneously in C ++

I am pleased with the = operator, which is automatically synthesized by the compiler. But I want it to be private and not want to inflate my code with page type definitions

Foo& Foo::operator= (const Foo& foo) { if (this == &foo) return *this; member1_ = foo.member1_; member2_ = foo.member2_; member3_ = foo.member2_; ... member1000_ = foo.member1000_; return *this; } 

Please, is there any way to do this?

+4
source share
2 answers

In C ++ 11, this is:

 class Foo { Foo& operator=(const Foo& source) = default; public: // ... }; 

Unfortunately, most compilers have not yet implemented this part of the new standard.

+8
source

Another option is to use the Pimpl idioms.

 class Foo { public: Foo() : pImpl(new FooImpl) {} // ... Foo public interface, same as before private: Foo& operator=(const Foo& source); //- Foo assignment operator is private struct FooImpl; boost::scoped_ptr<FooImpl> pImpl; }; struct FooImpl { // ... all the private data members that use to be in Foo // Note: using the compiler generated copy assignment operator }; 

The copy assignment operator is private from POV of Foo clients, but you can still use the compiler generated using FooImpl. A compromise arises when implementing the member functions of Foo, because now you have to access the data through the pImpl pointer.

+1
source

Source: https://habr.com/ru/post/1392986/


All Articles