I'm working out an "Any" class by myself. As following code shown, I have two questions.
#include <assert.h>
#include <iostream>
#include <typeinfo>
class Test{};
class Any {
public:
template<typename DataType>
explicit Any(DataType&& in) {
Test t;
std::cout
<< typeid(t).name() << " "
<< typeid(in).name() << " "
<< typeid(Test()).name();
std::cout << " move";
}
template<typename DataType>
explicit Any(const DataType& in) {
Test t;
std::cout
<< typeid(t).name() << " "
<< typeid(in).name() << " "
<< typeid(Test()).name();
std::cout << " copy";
}
};
int main()
{
Test t;
Any a(t);
}
Compilation command is
g++ main.cpp -std=c++11
The output is
4Test 4Test F4TestvE move
- Why does c++ choose move construct rather than copy construct? "t" is an instance of Test which it's not a rvalue.
- Why typeid(in) and typeid(Test()) is not same? They are both rvalue.
Thanks a lot.
The 1st constructor overload takes forwarding reference and could accept both lvalues and rvalues. (Hence it's not move constructor.) For
Any a(t);it's an exact match, while for the 2nd overloadtneeds to be converted toconst.Test()is a function type, which returnsTestand takes nothing, thustypeid(Test())gives different result.