C++ 为什么这个动作如此贪婪?
我有以下代码:C++ 为什么这个动作如此贪婪?,c++,c++11,copy-constructor,move-semantics,move-constructor,C++,C++11,Copy Constructor,Move Semantics,Move Constructor,我有以下代码: #include <iostream> class foo_class { std::string value; public: foo_class(const foo_class& v) : value{v.value} { std::cout << "copy constructor" << std::endl; } foo_class(foo_class&& v)
#include <iostream>
class foo_class {
std::string value;
public:
foo_class(const foo_class& v) : value{v.value} {
std::cout << "copy constructor" << std::endl;
}
foo_class(foo_class&& v) : value{std::move(v.value)} {
std::cout << "move constructor" << std::endl;
}
~foo_class() {
std::cout << "destructor" << std::endl;
}
foo_class(std::string v) : value{std::move(v)} {
std::cout << "type constructor" << std::endl;
}
};
struct Data {
foo_class a;
foo_class b;
};
int main() {
std::string c = "3";
Data x{c,c+"3"};
return 0;
}
这意味着复制构造函数根本没有被使用,即使它应该用于结构数据的构造函数的第一个参数
接下来,如果我删除复制构造函数,根据我的编译器,代码仍然是合法的,但在我看来应该是非法的,因为在传递数据构造函数的第一个参数时,我没有强制转换为&(使用std::move)
我的问题很简单:
为什么会发生这种情况?
我遗漏了什么吗?因为
foo\u类
对象是在
Data x{c,c+"3"};
他们都是临时工。所以他们调用移动构造函数而不是复制构造函数
type constructor // 1. Construct a temporary foo_class object out of string "c" for a
move constructor // 2. Move the temporary object created above to x.a
destructor // 3. Destruct the temporary foo_class object created in 1
type constructor // 4. Same as 1, but the object is for b, and the string "33"
move constructor // 5. Same as 2, moved to x.b
destructor // 6. Destruct the temporary foo_class object created in 4
destructor // 7. Destruct x.b
destructor // 8. Destruct x.a
因为
foo_类
对象是在
Data x{c,c+"3"};
他们都是临时工。所以他们调用移动构造函数而不是复制构造函数
type constructor // 1. Construct a temporary foo_class object out of string "c" for a
move constructor // 2. Move the temporary object created above to x.a
destructor // 3. Destruct the temporary foo_class object created in 1
type constructor // 4. Same as 1, but the object is for b, and the string "33"
move constructor // 5. Same as 2, moved to x.b
destructor // 6. Destruct the temporary foo_class object created in 4
destructor // 7. Destruct x.b
destructor // 8. Destruct x.a
你为什么认为它应该是一个副本?这两个参数都经过转换,所以有两个临时变量可以移动。这是否意味着如果不在数据中声明转发构造函数,我就无法实现到std::string value的完美转发?“完美转发”是一个适用于模板函数的概念,而您没有。代码将字符串的内容直接移动到
x
,这与一组完美的转发函数所做的相同。虽然您的类型构造函数中有一个额外的副本,但为什么您认为它应该是一个副本?这两个参数都经过转换,所以有两个临时变量可以移动。这是否意味着如果不在数据中声明转发构造函数,我就无法实现到std::string value的完美转发?“完美转发”是一个适用于模板函数的概念,而您没有。代码将字符串的内容直接移动到x
,这与一组完美的转发函数所做的相同。尽管在类型构造函数中有一个额外的副本。