template<typename T>
class Numeric
{
public:
Numeric() : val(T()) { cout << "ctor default\n"; }
explicit Numeric(const T& v) : val(v) { cout << "ctor value\n"; }
Numeric(const Numeric& v) : val(v.val) { cout << "copy ctor\n"; }
Numeric(Numeric&& v) { val = v.val; cout << "cmove\n"; v.val = 0; }
Numeric& operator=(const Numeric& v) { val = v.val; cout << "copy assignment\n"; return *this; }
Numeric& operator=(Numeric&& v) { val = v.val;cout << "amove\n"; return *this; }
~Numeric() { cout << "dtor\n"; };
private:
T val;
};
// ----------- main ------
Numeric<int> c1(Numeric<int>(2)); // calls the normal constructor instead of copy constructor
我希望复制构造函数被调用,但事实并非如此,而是调用了值初始化的构造函数。
这是怎么回事?似乎正在进行隐式转换,但我不明白为什么。
如果我明确地转换它,像这样
Numeric<int> c1(Numeric<int>(Numeric<int>(2)));
正在调用移动构造函数和析构函数。
最佳答案
啊哈,您无意中遇到了复制省略。参见 https://en.cppreference.com/w/cpp/language/copy_elision更多细节。该页面上的第一个示例就是您描述的确切情况。
只需将 main 更改为即可调用复制 ctors
Numeric<int> c0(2);
Numeric<int> c1(c0);
关于c++ - 调用值构造函数而不是复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911347/