给定类NamedType
,我想调用move-constructor:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <utility>
template<typename T, typename PARAMETER>
class NamedType {
public:
NamedType() { /*std::cout << "default ";*/ }
NamedType(T const &value) : value_(value) { /*std::cout << "parametrized ";*/ }
NamedType(NamedType const &other) : value_(other.value_) { std::cout << "copy "; }
NamedType(NamedType &&other) noexcept : value_(std::exchange(other.value_,0)) { std::cout << "move "; }
NamedType& operator=(NamedType const &rhs) { value_ = rhs.value_; std::cout << "copyAssign "; return *this; }
NamedType& operator=(NamedType &&rhs) { value_ = std::exchange(rhs.value_,0); std::cout << "moveAssign "; return *this; }
~NamedType() = default;
T const & Get() const { return value_; }
private:
T value_;
};
using Degree = NamedType<int, struct DegreeParameter>;
Degree GetRandom() {
return Degree{std::rand() % 100};
}
调用以下脚本时
int main() {
std::srand(std::time(0));
Degree degreeCopyAssign, degreeMoveAssign; // no output, since uninitialized
Degree degreeParametrized(1); // std::cout << degreeParametrized.Get() << std::endl;
Degree degreeCopy(degreeParametrized); std::cout << degreeCopy.Get() << std::endl;
Degree degreeUnknown(GetRandom()); std::cout << degreeUnknown.Get() << std::endl; // which constructor is called? why no implicit move?
Degree degreeMove(std::move(GetRandom())); std::cout << degreeMove.Get() << std::endl;
degreeCopyAssign = degreeCopy; std::cout << degreeCopyAssign.Get() << std::endl;
degreeMoveAssign = GetRandom(); std::cout << degreeMoveAssign.Get() << std::endl; // why implicit move here?
return 0;
}
未调用move-constructor,但我希望degreeUnknown
被调用。在那里叫哪个构造函数?
为什么移动命令隐式地被degreeMoveAssign
调用,而不被移动构造函数cf调用。 degreeMove
?
该脚本的示例输出为
copy 1
64
move 96
copyAssign 1
moveAssign 7
谢谢:)