C ++ push_back,非const复制构造函数 [英] c++ push_back, non const copy constructor

查看:80
本文介绍了C ++ push_back,非const复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个想推送到双端队列的类。问题是当我后退时我需要更改原始对象,因此我需要一个非const复制ctor。现在,如果我实现了我的const copy ctor被调用。如果我删除了const ctor,则会收到有关没有可用ctor的编译错误。如何通过传递原始结构的方式实现此目的?我需要修改它,因为当类超出范围时该类会破坏对象,并且我想告诉它在周围还有另一个实例时不要这样做。我不能使用boost,因为我的平台不支持boost。

I have a class that i want to push_back into a deque. The problem is when i push back i need the original object to be changed thus i need a non const copy ctor. Now if i implement that my const copy ctor gets called. If i removed the const ctor i get an compile error about no available ctors. How do i implement this in a way that i can modify the original struct when i pass it in? i need to modify it bc the class destructs objects when it goes out of scope and i would like to tell it not to do so when there is another instance around. I cant use boost since my platform doesnt support it.

推荐答案

您的问题是标准容器的基本要求是对象必须是复制可构造的。这不仅意味着它们具有副本构造函数,而且还意味着如果复制对象,则副本和原始对象是相同的。

Your problem is that a fundamental requirement of standard containers is that objects are copy-constructible. That not only means that they have a copy constructor, but that also means that if you copy the object, the copy and the original are the same.

但是,您的对象类似于move-constructor语义。也就是说,移动后,新对象拥有资源,而旧对象为空。从C ++ 03开始,deque不支持该功能。顺便说一下,这就是禁止将auto_ptr放入容器的相同原因。

Your object, however, resembles a move-constructor semantic. That is, after a move, the new object owns the resource, and the old object is empty. That's not supported by deque as of C++03. That is, by the way, the same reason that forbids putting auto_ptr into a container.

称为C ++ 0x的下一个C ++版本将通过引入特殊的move构造函数来支持这些move语义。在此之前,要想将其所有权放入标准容器中,就必须使用拥有所有权的对象。这意味着如果您复制对象,并且原始对象超出范围,则在所有副本都超出范围之前,不会释放拥有的资源。例如,考虑使用boost :: shared_ptr,或者如果您不想编写自己的类来对其进行管理,则可以将其包装到您的类中。

The next C++ version, called c++0x will support those move semantics by introducing special move constructors. Until then, you will have to use an object that shares ownership when you want to put it into a standard container. That means if you copy your object, and the original goes out of scope, the owned resource is not freed until all the copies go out of scope. Consider using boost::shared_ptr for example, or wrap it into your class, if you don't want to program your own class managing that.

这篇关于C ++ push_back,非const复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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