问题描述
我只是在玩耍以了解智能指针并尝试创建我的指针,但遇到一种我不完全了解的情况.这是代码:
I am just playing around to understand smart pointers and trying to make mine but I come across a situation that I do not fully understand. Here is the code:
#include <iostream>
template <class T>
class Holder
{
private:
T * obj;
public:
Holder(T * tt) : obj(tt)
{
std::cout << "ctor : " << tt->dummy << std::endl;
}
T * operator -> ()
{
return obj;
}
operator bool()
{
return obj;
}
T * const get() const
{
return obj;
}
void reset() {swap(0);}
void swap(T * other)
{
obj = other;
}
Holder & operator = (const Holder& holder)
{
obj = holder.get();
return *this;
}
Holder(const Holder & holder) : obj(holder.get()) {}
};
class A
{
public:
int dummy;
A(int a) : dummy(a) {}
};
int main ()
{
A * a = new A(1);
Holder<A> holder(a);
A * b = new A(2);
holder = b;
std::cout << holder->dummy << std::endl;
return 0;
}
编译代码,并在 holder = b;
行上调用 Holder
类的构造函数.我以为编译器会报错.它不是赋值运算符,但为什么要调用构造函数?
The code compiles and on the line of holder = b;
the constructor of Holder
class is called. I thought compiler would give an error. It is not the assingment operator but why is it calling constructor?
推荐答案
holder = b
尝试从 b
分配给 Holder
. b
的类型为 A *
,而 holder
的类型为 Holder< A>
.
holder = b
attempts to assign from b
to Holder
. b
is of type A*
, and holder
is of type Holder<A>
.
Holder
模板定义来自另一个具有相同 Holder
类型的实例的赋值,因此编译器从 A查找转换*
更改为 Holder< A>
.它会找到构造函数,并使用它.
The Holder
template defines assignment from another instance of the same Holder
type, so the compiler looks for a conversion from A*
to Holder<A>
. It finds the constructor, and uses that.
可能仅使用一个参数的构造函数可用于隐式转换,除非使用 explicit
关键字标记它们.
Constructors which may take exactly one argument may be used for implicit conversions, unless you tag them with the explicit
keyword.
这篇关于为什么赋值运算符调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!