什么时候用指针调用C++类构造函数
When is C++ Class Constructor called with pointer?
我对c++没有深入的了解
我已经实现了智能指针,以防止由原始指针引起的问题。(内存泄漏(
下面是智能指针的代码。
#ifndef SMARTPOINTER
#define SMARTPOINTER
class RC
{
private:
int count; // Reference count
public:
RC(){ count = 0; }
void AddRef()
{
// Increment the reference count
count++;
}
int Release()
{
// Decrement the reference count and
// return the reference count.
if(count==0) return 0;
return --count;
}
};
template < typename T > class SP
{
private:
T* pData; // pointer
RC* reference; // Reference count
public:
SP() : pData(0), reference(0)
{
// Create a new reference
reference = new RC();
// Increment the reference count
reference->AddRef();
}
SP(T* pValue) : pData(pValue), reference(0)
{
// Create a new reference
reference = new RC();
// Increment the reference count
reference->AddRef();
}
SP(const SP<T>& sp) : pData(sp.pData), reference(sp.reference)
{
// Copy constructor
// Copy the data and reference pointer
// and increment the reference count
reference->AddRef();
}
~SP()
{
// Destructor
// Decrement the reference count
// if reference become zero delete the data
if(reference->Release() == 0)
{
delete pData;
delete reference;
}
}
T& operator* ()
{
return *pData;
}
T* operator-> ()
{
return pData;
}
SP<T>& operator = (const SP<T>& sp)
{
// Assignment operator
if (this != &sp) // Avoid self assignment
{
// Decrement the old reference count
// if reference become zero delete the old data
if(reference->Release() == 0)
{
delete pData;
delete reference;
}
// Copy the data and reference pointer
// and increment the reference count
pData = sp.pData;
reference = sp.reference;
reference->AddRef();
}
return *this;
}
};
#endif // SMARTPOINTER
我的问题如下
当使用以下中的智能指针类时
SP<MyObject> ptrObject; //MyObject class is the custom class.
MyObject *ptr = new MyObject;
ptrObject = ptr; //This invokes the SP(T *) constructor.. why?
//Though operator = ( T*) is not defined.
此时,虽然没有定义operator=(T*)
函数,但为什么要调用智能指针的构造函数SP(T*pValue(?我认为构造函数是在创建类对象时调用的
请解释一下,谢谢。
每当在不接受某个类型T1但接受某个其他类型T2的上下文中使用某个类型的表达式时,都会执行隐式转换
特别是:
- 当表达式用作具有期望T2的运算符的操作数时
- 当初始化类型为T2的新对象时,在返回T2的函数中包括return语句
- 当在切换语句中使用该表达式时(T2是积分类型(
- 当表达式用于if语句或循环时(T2为布尔(
这对您有帮助
https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/implicit_conversion_sequences.htm
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为