How to use operator = with anonymous objects in C ++?

I have a class with an overloaded operator:

IPAddress& IPAddress::operator=(IPAddress &other) { if (this != &other) { delete data; this->init(other.getVersion()); other.toArray(this->data); } return *this; } 

When I try to compile this:

 IPAddress x; x = IPAddress(IPV4, "192.168.2.10"); 

I get the following error:

 main.cc: In function 'int main()': main.cc:43:39: error: no match for 'operator=' in 'x = IPAddress(4, ((const std::string&)(& std::basic_string<char>(((const char*)"192.168.2.10"), ((const std::allocator<char>&)((const std::allocator<char>*)(& std::allocator<char>())))))))' IPAddress.h:28:20: note: candidate is: IPAddress& IPAddress::operator=(IPAddress&) 

However, these two works work fine (although they serve me no purpose):

 IPAddress x; IPAddress(IPV4, "192.168.2.10") = x; 

-

 IPAddress x; x = *(new IPAddress(IPV4, "192.168.2.10")); 

What's happening? Am I guessing something wrong regarding how the assignment operator works?

+4
source share
2 answers

The right side of the assignment operator must accept const IPAddress& .

Temporary objects can bind to constant links, but not to non-constant links. This is why x = IPAddress(IPV4, "192.168.2.10"); does not work.

IPAddress(IPV4, "192.168.2.10") = x; works because it is legal to call member functions on temporary objects.

+5
source

The assignment operator is defined using const :

 IPAddress& IPAddress::operator=(const IPAddress &other) 

Your temporary cannot link to a non-constant reference, since it theoretically breaks down before calling the assignment operator (this may not happen due to optimization, do not rely on it).

+4
source

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


All Articles