使用C ++学习复制语义 [英] Getting around copy semantics in C++

查看:121
本文介绍了使用C ++学习复制语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

class A
{

};

int main()
{
    std::vector<A> test;
    test.push_back(A());
}

构造函数和析构函数将被调用两次,对象将被复制,现在不仅是可能性能的性能,它也可能导致运行时错误,特别是如果有一些清理在析构函数。我通常会解决这个问题的方法是创建一个指针的向量代替:

The constructor and destructor will be called twice, also memory will be allocated twice and the object will copied, now not only is that potentially bad for performance it could also lead to run time errors, especially if there's some cleanup going on in the destructor. The way i'd usually get around this is to just create a vector of pointers instead :

std::vector<A*> test;
test.push_back(new A());

我的问题是两倍,这是常见的做法,还是有更好的方法?
如果这是一个重复,请让我知道,我会关闭的问题,但我找不到任何搜索。

My question is two fold, is this common practice and is it good practice? Or is there a better way? If this turns out to be a dupe please let me know and i'll close the question, but I couldn't find anything on searching.

推荐答案

使用 emplace_back

std::vector<A> test;
test.emplace_back();
//test.emplace_back(constructor, parameters);

这样, A

编辑:澄清对问题的意见 - 不,这不会改变从 push_back 如果你传递一个临时的。例如,

To clarify on the comments on the question - No, this will not change from push_back if you pass it a temporary. For instance,

test.emplace_back(A{});

在C ++ 11中,会导致构造,移动和销毁临时A如果您使用 push_back

Will, in C++11, cause a temporary A to be constructed, moved and destroyed, as if you used push_back.

这篇关于使用C ++学习复制语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆