Sunday, February 16, 2014

The under-evaluated delete specifier

As you should know by now in C++11 we are able disable certain signatures in our classes. Most of the time this is used to disable copy constructor and assignment operators


this way is much better than the old way where the programmer had to declare private both member and then not implement them getting an error either at compile time or either at linking time.

The delete specifier can disable some automatic overloads consider indeed the following code

it works perfectly but if we do not want that automatic conversion (note that explicit can not be used here) then the delete specifier can come in handy

A typical mistake in C++ is to store a reference (or a pointer for the matter) to a temporary object leading to a disaster. This mistake is one of the argument java guys put on the table when they are arguing against C++.

The following class is a perfectly working class but used wrongly can store a reference to a temporary object


The delete specifier can help us again indeed we can disable the constructor with a rvalue reference and avoid such use:


now the code above will lead to a compilation error in case we are trying to build the class with a temporary string, you should note that a "const &&" is needed, indeed without the const specifier passing a "const std::string foo()" will not led to a compilation error

Time to add to my coding rules a new rule!

5 comments:

Jorge said...

you should note that a "const &&" is needed, indeed without the const specifier passing a "const std::string foo()" will not led to a compilation error


Why is that?

Ivan Čukić said...

Temporaries are not always r-value references.

Something like this will still expose the flaw of having a reference member:

CrashDestination test()
{
std::string s{"Hello"};
return CrashDestination(s);
}

Ahmad Urpan Rifai said...

N  FOLL-BACK

I    http://hollosys.blogspot.com/

C   

E   ARTIKEL

Affity Solutions said...

Thanks for your ideas. You can also find the details on Affity Solutions, at the C++ Developers. The main object of the Affity Solutions is to provide quality web services and is among the few software development company in Nagpur.

awais kamran said...

For new programmers, its always difficult to use specifiers either they are delete or access specifiers.
Learn C++ in Urdu