嗨(英语不是我的第一语言,即使我犯错也请理解我!谢谢!)
我正在编写一个可以包含指针的模板类。
template <typename T>
class SmartPtr {
private:
T value;
public:
SmartPtr() {};
~SmartPtr() {};
SmartPtr(T* a)
{
this->value = *a;
}
SmartPtr(SmartPtr* a)
{
this->value = a->get_Value();
}
SmartPtr(SmartPtr const* a)
{
this->value = a->get_Value();
}
T get_Value()const{
return this->value;
}
};
这是名为SmartPtr的模板类,
class Test
{
public:
Test() { std::cout << "Test::Test()" << std::endl; }
Test(Test const&) { std::cout << "Test::Test(Test const&)" << std::endl; }
~Test() { std::cout << "Test::~Test()" << std::endl; }
Test& operator=(Test const&)
{
std::cout << "Test& Test::operator=(Test const&)" << std::endl;
return *this;
}
void print() const { std::cout << "Test::print() const" << std::endl; }
void print() { std::cout << "Test::print()" << std::endl; }
};
这是我的Test课程。
当我宣布
时 在main.cpp中 SmartPtr<Test> ptr_t1 = SmartPtr<Test>(new Test);
,
编译后的结果是
Test::Test()
Test::Test()
Test& Test::operator=(Test const&)
Test::~Test()
但我想得到的结果是
Test::Test()
Test::~Test()
在这种情况下是否需要编写特定的模板类复制构造函数?
非常感谢您的耐心等待!
答案 0 :(得分:2)
原因是因为SmartPtr内部有value
成员变量:
template <typename T>
class SmartPtr {
private:
T value; // here T is of class Test
... other stuff ...
}
宣布
时SmartPtr<Test> ptr_t1 = SmartPtr<Test>(new Test);
ptr_t1
是构造,因此构造了它的值。这是第一个Test()
构造函数调用。
第二个构造函数是new Test
(显然)。
然后,构建SmartPtr
,在this->value = *a;
内部调用Test()
赋值运算符。
最后,SmartPtr<Test>(new Test)
对象被破坏,在内部value
对象上调用析构函数。
另请注意,因为调用了new Test
但没有delete
,也存在内存泄漏。
答案 1 :(得分:0)
为了只调用构造函数和析构函数,只需直接调用构造函数:
SmartPtr ptr_t1(新测试);
此外,您的SmartPtr类应存储指针而不是值。该值可以驻留在对new调用分配的内存中。而不是:
私人:T值;
写:
私人:T *值;
这将确保构造函数不会复制该值,而只是指向该值。该值仍将驻留在new分配的内存中。