简体   繁体   中英

defining explicit overloaded constructor issue

I have following class that some of the operators are overloaded:

class CLASS1
{
       CLASS1();
       CLASS1(const CLASS1 &obj);

   CLASS1 operator +(const CLASS1 &obj) {
       CLASS1 srcObj;
       // doing add stuff here
           return srcObj;
       }

   void func()
   {
   CLASS1 boj = // some method which returns CLASS1 obj.
   }


   CLASS1& operator =(const CLASS1 &obj) {
       // copy properties
       }
}

Ok, this works fine. but after awhile I decided to make my class explicit to avoid implicit conversions. Therefore, I've made it this way:

class CLASS1
{
       explicit CLASS1();
       explicit CLASS1(const CLASS1 &obj);

   CLASS1 operator +(const CLASS1 &obj) {
       CLASS1 srcObj;
       // doing add stuff here
           return srcObj;          // compiler gives non-matching errors
   }

   void func() {
       CLASS1 boj = somemethods(); // compiler gives non-matching errors
   }

   CLASS1& operator =(const CLASS1 &obj) {
       // copy properties
       }
}

Now, the compiler gives 'no matching function to call...' error (specified in the code above), in spite of I've explicitly overloaded assignment operator. Where is my mistake?

When you return an object by value the copy-constructor is called implicitly . If you say it's not allowed to be called implicitly you will get an error.

You should not use explicit for your default, copy or move constructors. Or for constructors taking more than one argument. Only for constructors taking a single argument (with the noted exceptions).

Technically speaking, when returning an object from a method, an object you receive outside method call is actually a copy of an object you declare inside method. So compiler must have a permitted way to "transfer contents" from in-method object to method result. Since in-method instance is no longer needed, the move is the best approach (yes, you need to add move constructor):

CLASS1(CLASS1&& obj);

This will allow you to forbid implicit conversions, while maintaining the ability to have temporary objects.

In real life, the afforementioned copy/move will likely be optimized away by RVO/NRVO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM