简体   繁体   中英

c++ push_back, non const copy constructor

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.

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.

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.

如果你没有做什么狡猾的资源(见其他意见),然后让你想改变可变将允许你改变它在一个const函数的成员变量。

Depending on what you are trying to do (more details would be nice), you can either modify the object before/after you call push_back or write a simple wrapper class that takes a pointer to your class and can be inserted into a deque . This object can then do the appropriate thing to your class on construction/destruction/etc.

You can't do what you're trying to do. You'll have to use pointers, either plain or smart (but not auto_ptr<>). Why can't you use Boost smart pointers? They're pretty lightweight, and should work in all reasonably standard C++ compilers. You don't have to use all of Boost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM