b**n 发帖数: 289 | 1 我有一个GVector 的Class,它有一个copy constructor是用template的。
template
class GVector{
public:
template GVector (const GVector& rhs): length_(rhs.length()
){
ptr_ = new (nothrow) T[length_];
assert(ptr_);
std::copy(&rhs(0), &rhs(0) + length_, ptr_);
}
但我每次在下列情况下(X = T)都会出现运行期的内存错误
GVector v(3);
GVector v2(v);
但如果在X != T时,就没有问题,比如:
GVector v(3);
GVector vi(v);
请问这是怎么回事? 我现在在把我以前写的一些class改成template的,结果问题好多
啊!
谢谢帮忙。 | t****t 发帖数: 6806 | 2 This is due to the incorrect use of terminology.
"它有一个copy constructor是用template的。"
1. "Copy constructor" means the special, non-template constructor, if the
first parameter is of type X&, const X&, volatile X&, or const volatile X&(,
and other parameter can be omitted). Therefore, if the parameter is of type
T& (T!=X), it is not a copy constructor; if a constructor is a template, it
is not a copy constructor. Repeat: copy constructor is never a template.
2. Copy constructor is implicitly define
【在 b**n 的大作中提到】 : 我有一个GVector 的Class,它有一个copy constructor是用template的。 : template : class GVector{ : public: : template GVector (const GVector& rhs): length_(rhs.length() : ){ : ptr_ = new (nothrow) T[length_]; : assert(ptr_); : std::copy(&rhs(0), &rhs(0) + length_, ptr_); : }
| b**n 发帖数: 289 | 3 This is really helpful. First time to hear this. Thank you very much. |
|