c++ - 在将参数传递给基类时使用 std::move()

标签 c++ constructor c++11 move-semantics

忽略做我所描述的事情的合理性,使用 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 处使用 bsfs >//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/

相关文章:

c++ - 使用 (c++11) 声明类型时将 __declspec(dllimport) 关键字放在哪里

c++ - 为什么模板类型推导在这里失败了?

c++ - 为什么 C++ bool var 默认为 true?

c++ - VS2015 : using/Wall from the CLI but disabling warning in some file (eg: thoses in Microsoft Visual Studio 14. 0)

c++ - 算法库

c++更改数字位?

c++ - 抽象类虚基类的初始化

javascript - 这是普通函数、构造函数还是两者都不是?

java - 在构造函数中使用公共(public)最终成员变量和可重写方法

c++ - 使用固定整数类型的安全性