c++ - Does the compiler avoid a copy when returning a string that is taken as const reference? -
i wander if compiler optimize away copy in following situation. have class resource member string may few kb large. want have public member of class access string , not sure if should have member returning reference or value. suppose choose return value so
class { public: a(); ~a(); std::string getstring() { return str; } private: std::string str; } int main() { *a = new a; const std::string& str = a->getstring(); std::cout << str; }
will compiler optimize , avoid copy if take result const std::string&
in main
?
it's remotely possible, highly unlikely compiler optimize away copy in use case.
observe if copy gets optimized away, caller's temporary gets bound const
reference object's class member. , const
means referenced value cannot changed.
with code shown in question, it's possible compiler can prove nothing can possibly change contents of class member while const
reference remains in scope, , safe make optimization.
but things muddy quickly, in more generalized case. if there other class methods can potentially change contents of referenced class member, if there calls during const
reference's lifetime functions or methods definition not visible; result compiler have no way of knowing if it's possible referenced class member modified during const
reference's entire execution scope, , forced make copy of string, in order guarantee const
-ness.
a compiler free make optimization result in no visible, observed changes in well-formed program. if compiler cannot prove optimization results in no visible, observable changes optimization not performed.
p.s. note "modification" includes destruction. proposed optimization binds const
reference object in dynamic scope. if there intervening calls delete
-- explicitly or implicitly part of calls various library container methods -- compiler have prove delete
d object cannot object bound const
reference.
Comments
Post a Comment