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

2021-04-20 16:31:41 +08:00
 auto8888

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

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

1214 次点击
所在节点    C++
5 条回复
yazoox
2021-04-20 16:39:58 +08:00
是不是 vector 扩容?
auto8888
2021-04-20 16:48:25 +08:00
@yazoox 好像是的,加了 vt.reserve(10); 只有两个 right copy 了,所以 vector 扩容默认用的复制构造吗
baiihcy
2021-04-20 16:51:29 +08:00
试试用 emplace_back 代替 push_back
lcdtyph
2021-04-20 16:56:40 +08:00
@auto8888
因为你的移动构造不是 noexcept 的,加上限定就可以让 std::vector 调用了
Lordon
2021-04-21 21:45:36 +08:00
@baiihcy 试过了 结果一样

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/771941

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX