
大佬们好,小弟请教两个问题
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
1 yazoox 2021-04-20 16:39:58 +08:00 是不是 vector 扩容? |
2 auto8888 OP @yazoox 好像是的,加了 vt.reserve(10); 只有两个 right copy 了,所以 vector 扩容默认用的复制构造吗 |
3 baiihcy 2021-04-20 16:51:29 +08:00 试试用 emplace_back 代替 push_back |
4 lcdtyph 2021-04-20 16:56:40 +08:00 via iPhone @auto8888 因为你的移动构造不是 noexcept 的,加上限定就可以让 std::vector 调用了 |