简体   繁体   中英

C++ auto_ptr and copy construction

If I have a class

template <typename T>
struct C {
...

private:
  auto_ptr<T> ptr;
};

How do I define the copy constructor for C:

It cannot be

template <typename T>
C<T>::C(const C& other) 

because I want to if I copy the auto_ptr from other, I have changed other by removing ownership. Is it legal to define a copy constructor as

template <typename T>
C<T>::C(C& other) {}

如果要防止所有权转让和/或复制,可以定义复制构造函数和赋值运算符private ,从而禁止类的用户复制或分配对象。

Do you actually want to copy your class's state or transfer it? If you want to copy it then you do it just like any other class with pointers in it:

template < typename T >
C<T>::C(C const& other) : ptr(new T(*other.ptr)) {} // or maybe other.ptr->clone()

If you actually want to transfer ownership of the pointer you could do it with a non-const "copy" constructor but I'd recommend you do something that's more obvious at the call site; something that tells people reading the code that ownership has transfered.

There's no such thing as a "standard" copy constructor, but people do expect them to behave a certain way. If your object is going to do any transferring of ownership on copy, then it's a bad idea to make a copy constructor that obscures this fact. A better approach would be to create a method that makes this clear. (You could call it CloneAndTransfer or something similar.)

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