auto8888
V2EX  ›  C++

请教两个问题,关于类成员赋初值和 std::vector 的 pushback()方法与移动构造

  •  
  •   auto8888 · Apr 20, 2021 · 2913 views
    This topic created in 2029 days ago, the information mentioned may be changed or developed.

    大佬们好,小弟请教两个问题

    1.类成员赋初值是在类内定义还是在初始化列表定义好? 记得有本书讲过,不记得了。。。。

    比如

    #include <vector>
    #include <iostream>
    class TestA
    {
        public:
        TestA() :a(11)  //方法 1
        {
        std::cerr << "test1 cons"<< std::endl;
        }
        int a = 10; //方法 2
        TestA(const TestA &ta)
        {
        a = ta.a;
        std::cerr << "test1 left copy"<< std::endl;
    
        }
        TestA(TestA &&ta)
        {
        a = ta.a;
        std::cerr << "test1 right copy"<< std::endl;
        }
    };
    int main(int argc, char *argv[])
    {
       TestA aaa;
       TestA bbb;
       std::cerr << "~~~~"<< std::endl;
       std::vector <TestA > vt;
       vt.push_back(std::move(aaa));
       vt.push_back(std::move(bbb));
       return 0;
    }
    

    2.上面程序输出

    test1 cons
    test1 cons
    ~~~~
    test1 right copy
    test1 right copy
    test1 left copy
    

    为啥还输出了一次 left copy?就很怪 如果把 TestA(const TestA &ta)注释掉,就会出现 3 次 right copy

    5 replies  •  2021-04-21 21:45:36 +08:00
    yazoox
    yazoox
    Apr 20, 2021
    1
    是不是 vector 扩容?
    auto8888
    auto8888
    OP
    Apr 20, 2021
    2
    @yazoox 好像是的,加了 vt.reserve(10); 只有两个 right copy 了,所以 vector 扩容默认用的复制构造吗
    baiihcy
    baiihcy
    Apr 20, 2021
    3
    试试用 emplace_back 代替 push_back
    lcdtyph
    lcdtyph
    Apr 20, 2021 via iPhone
    4
    @auto8888
    因为你的移动构造不是 noexcept 的,加上限定就可以让 std::vector 调用了
    Lordon
    Lordon
    Apr 21, 2021
    5
    @baiihcy 试过了 结果一样
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1187 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:45 · PVG 01:45 · LAX 09:45 · JFK 12:45
    ♥ Do have faith in what you're doing.