Quick A: Because it performs worse than C++98 for common types like string
and vector.
The preferred way to optimize for rvalues is to add a &&
overload.
Fresh on SO:
Why is value taking setter member functions not recommended in Herb Sutter's CppCon 2014 talk (Back to Basics: Modern C++ Style)?
In Herb Sutter's CppCon 2014 talk Back to Basics: Modern C++ Style he refers on slide 28 (a web copy of the slides are here) to this pattern:
class employee { std::string name_; public: void set_name(std::string name) noexcept { name_ = std::move(name); } };He says that this is problematic because when calling
set_name()
with a temporary, noexcept-ness isn't strong (he uses the phrase "noexcept-ish").Now, I have been using the above pattern pretty heavily in my own recent C++ code mainly because it saves me typing two copies of set_name() every time -- yes, I know that can be a bit inefficient by forcing a copy construction every time, but hey I am a lazy typer. However Herb's phrase "This noexcept is problematic" worries me as I don't get the problem here: std::string's move assignment operator is noexcept, as is its destructor, so set_name() above seems to me to be guaranteed noexcept. I do see a potential exception throw by the compiler before set_name() as it prepares the parameter, but I am struggling to see that as problematic.
Later on on slide 32 Herb clearly states the above is an anti-pattern. Can someone explain to me why lest I have been writing bad code by being lazy?
Add a Comment
Comments are closed.