In the following simple code I return a function local object from a function (factory function). Does the C++ standard guarantee in every case that this object is being returned as an rvalue reference or are there exceptions I have to look out for?
#include <cstdio>
template <typename T>
struct vectorlike
{
vectorlike() = default;
~vectorlike() {
if (ptr_) {
delete ptr_;
}
}
vectorlike(const vectorlike& other) {
printf("%s(&) called!\n", __func__);
}
vectorlike(vectorlike&& other) {
printf("%s(&&) called!\n", __func__);
}
auto operator=(const vectorlike& other) -> vectorlike& {
printf("copy %s(&) called!\n", __func__);
ptr_ = new T(*other.ptr_);
return *this;
}
auto operator=(vectorlike&& other) noexcept -> vectorlike& {
printf("move %s(&&) called!\n", __func__);
ptr_ = other.ptr_;
other.ptr_ = nullptr;
return *this;
}
vectorlike(int i) {
ptr_ = new T(i);
}
T* ptr_;
};
template <typename T>
auto vector_factory() {
vectorlike<T> ret{2};
return ret;
}
int main()
{
vectorlike<int> hello;
hello = vector_factory<int>();
}
Output:
move operator=(&&) called!