忽略做我所描述的事情的合理性,使用 std::move()
函数是否可以在用于将参数传递给基本构造函数时缩短构造时间?
struct Bar {
Bar(std::string);
std::string _s;
}
struct Foo : public Bar {
Foo(std::string);
}
struct Bar(std::string bs) : _s(std::move(bs)) {
// 1
}
struct Foo(std::string fs) : Bar(std::move(fs)) {
// 2
}
所以在这个例子中,Foo
的构造函数中使用的 move()
是否阻止了对字符串的额外复制?
为了澄清,这种设计是否意味着不应尝试在点 //1
和 处使用
,但是在这两个地方都使用 bs
和 fs
>//2_s
会安全吗?
最佳答案
为了找出答案,我用一个伪造的 String
类重新编写了您的示例,如下所示:
#include <iostream>
struct String
{
String() {}
String(const String&) {std::cout << "String(const String&)\n";}
String& operator=(const String&)
{std::cout << "String& operator=(const String&)\n"; return *this;}
String(String&&) {std::cout << "String(String&&)\n";}
String& operator=(String&&)
{std::cout << "String& operator=(String&&)\n"; return *this;}
};
struct Bar {
Bar(String);
String _s;
};
struct Foo : public Bar {
Foo(String);
};
Bar::Bar(String bs) : _s(std::move(bs)) {
// 1
}
Foo::Foo(String fs) : Bar(std::move(fs)) {
// 2
}
int main()
{
Foo f{String()};
}
对我来说,这是打印出来的:
String(String&&)
String(String&&)
但是,如果我从 Foo
构造函数中删除此 std::move
,打印输出将更改为:
String(const String&)
String(String&&)
所以假设 String(String&&)
比 String(const String&)
快,前者更快。否则,不。
And for clarification, does this design mean no attempt should be made to use bs and fs at points // 1 and // 2, but using _s would be safe in both places?
正确。
关于c++ - 在将参数传递给基类时使用 std::move(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13515999/