gpt4 book ai didi

C++模板类,具体情况如何声明拷贝构造函数?

转载 作者:行者123 更新时间:2023-11-28 01:41:59 27 4
gpt4 key购买 nike

嗨(英语不是我的第一语言,即使我有错误也请理解我!谢谢!!)

我正在编写一个可以包含指针的模板类。

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; }
};

这是我的测试课。

当我声明

SmartPtr<Test> ptr_t1 = SmartPtr<Test>(new Test);在我的 main.cpp 中,

编译后的结果是

Test::Test()
Test::Test()
Test& Test::operator=(Test const&)
Test::~Test()

但是我想要得到的结果是

Test::Test()
Test::~Test()

在这种情况下是否需要编写特定的模板类复制构造函数?

非常感谢您的耐心等待!

最佳答案

原因是因为在 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 , 也有内存泄漏。

关于C++模板类,具体情况如何声明拷贝构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46796670/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com