I've been digging around ref-qualifiers a bit, following on a previous question.
Given the code sample below;
#include <iostream>
#include <string>
#include <utility>
struct A {
std::string abc = "abc";
std::string& get() & {
std::cout << "get() &" << std::endl;
return abc;
}
std::string get() && {
std::cout << "get() &&" << std::endl;
return std::move(abc);
}
std::string const& get() const & {
std::cout << "get() const &" << std::endl;
return abc;
}
std::string get() const && {
std::cout << "get() const &&" << std::endl;
return abc;
}
};
int main()
{
A a1;
a1.get();
const A a2{};
a2.get();
A().get();
const A a3{};
std::move(a3).get();
}
And the output is as you would expect:
get() &
get() const &
get() &&
get() const &&
This compiles and runs with clang and gcc 4.9.1 (not 4.9.0 though). Live sample here.
In general code (the sample is there to see how the code compiles and runs).
- What would the purpose of the
const &&
ref-qualifier on a method be?
The method is unable to modify the contents on the object (it is const
), an attempt to return std::move(abc);
from the const &&
method doesn't actually move the std::string
at all. Presumably you would want to be able modify the object, since it's an r-value and won't be around for long. If the const &&
qualified method were to be removed, the code std::move(a3).method()
would bind to the const &
qualified method, which would make sense.
- What, if any, would the implied semantic difference be between a method qualified as
const &
and one qualified asconst &&
? I.e. how would the implementation vary or why would you want both? - Would the
std::string
truely be able to be "moved" out of the temporary object? - What would a "canonical" signature look like for
std::string get() const &&
in this case?