【发布时间】:2016-02-05 13:30:10
【问题描述】:
我正在编写一个类似于 unique_ptr 的类,称为 StackGuard,并尝试创建两个复制构造函数:
template<typename T>
class StackGuard{
T* thePtr; //To store the raw pointer.
//something here...
StackGuard(StackGuard<T>& newPtr) throw();
StackGuard(StackGuard<T> newPtr) throw(); //I know this is not the right way
//something here...
};
template<typename T>
StackGuard<T>::StackGuard(StackGuard<T>& newPtr) throw(){
thePtr = newPtr.thePtr;
newPtr.thePtr = NULL;
}
template<typename T>
StackGuard<T>::StackGuard(StackGuard<T> newPtr) throw(){
thePtr = newPtr.thePtr;
newPtr.thePtr = NULL;
}
但它不起作用。编译器说
error: invalid constructor; you probably meant ‘StackGuard<T> (const StackGuard<T>&)’
StackGuard(StackGuard<T> newPtr) throw();
^
error: prototype for ‘StackGuard<T>::StackGuard(StackGuard<T>)’
does not match any in class ‘StackGuard<T>’
StackGuard<T>::StackGuard(StackGuard<T> newPtr) throw(){
^
error: candidates are: StackGuard<T>::StackGuard(const StackGuard<T>&)
StackGuard<T>::StackGuard(const StackGuard<T>& newPtr) throw(){
^
error: StackGuard<T>::StackGuard(T*)
StackGuard<T>::StackGuard(T* guarded = NULL) throw() {
我有想过这个错误,但不知道对不对。
我的想法是:
传值拷贝构造函数需要使用拷贝构造函数来拷贝参数,在这种情况下,它会递归调用自身,导致无限调用。
我也想知道,为什么编译器会给出“与类中的任何内容不匹配”错误,因为它有匹配项。
【问题讨论】:
-
“copy-constructor”和“unique_ptr like”不兼容……后者只能移动。
-
StackGuard(StackGuard<T> newPtr)不是复制构造函数;复制构造函数只能通过左值引用接受它们的参数。 .我什至不认为这是一个合法的功能
标签: c++ copy-constructor pass-by-value