c++ - static_cast<> behaviour on class with implicit conversion operator that returns a const reference -
i have following class (stripped down contain relevant parts):
#include <string> class text { private: std::string _text; public: text(std::string&& text) : _text(std::move(text)) { } operator const std::string&() const { return _text; } };
my question is: if want obtain const std::string&
, can without penalty:
text text("fred"); auto& s = static_cast<std::string>(text);
or construct intermediate std::string
end getting reference to? there standard approach kind of scenario? reasonably new c++.
no, when you're calling static_cast<std::string>(text)
, you're calling implicitly defined copy constructor , creating temporary object.
however, if calling
auto& s = static_cast<const std::string&>(text);
,then correctly calling explicit conversion operator operator const noisy&()
.
let's try out
struct noisy { noisy() { std::cout << "default construct" << std::endl; } noisy(const noisy&) { std::cout << "copy construct" << std::endl; } noisy(noisy&&) { std::cout << "move construct" << std::endl; } noisy& operator=(const noisy&) { std::cout << "c-assign" << std::endl; return *this; } noisy& operator=(noisy&&) { std::cout << "m-assign" << std::endl; return *this; } ~noisy() { std::cout << "destructor" << std::endl; } }; class text { public: text(noisy&& text) : _text(std::move(text)) {} operator const noisy&() const { return _text; } private: noisy _text; };
test 1
int main() { text text(noisy{}); const auto& s = static_cast<noisy>(text); // needs 'const' bind temporary. }
default construct
move construct
destructor
copy construct
destructor
destructor
test 2
int main() { text text(noisy{}); auto& s = static_cast<const noisy&>(text); }
default construct
move construct
destructor
destructor
note: compiled using option -fno-elide-constructors
avoid copy elision optimizations.
Comments
Post a Comment