【问题标题】:Using std::move() when passing an argument to a base class将参数传递给基类时使用 std::move()
【发布时间】:2012-11-22 15:37:54
【问题描述】:

忽略我所描述的理智,使用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// 2 点上使用 bsfs,但在这两个地方使用 _s 是安全的?

【问题讨论】:

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


    【解决方案1】:

    为了找出答案,我用一个假的 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&amp;&amp;)String(const String&amp;) 快,则前者更快。否则,不。

    为了澄清,这种设计是否意味着不应该进行任何尝试 在点 // 1 和 // 2 处使用 bs 和 fs,但使用 _s 是安全的 在这两个地方?

    正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2022-01-21
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多