我在在C 中实现智能指针进行分配时遇到了困难。我的代码应该创建两个SmartPointers。第一个点为1,第二点最初为3,但已更改为10。我的代码应打印出
intone:1inttwo:10
,但它打印出
intone:10Inttwo:4919984
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <exception>
using namespace std;
template <typename T>
class SmartPointer
{
public:
SmartPointer(T in)
{
try
{
if(in<0)
{
throw "SmartPointer does not handle negative numbers";
}
T * val = ∈
this->data = val;
}
catch(exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
}
~SmartPointer()
{
delete data;
}
T getValue();
void setValue(T val);
private:
T*data;
};
template <typename T> T SmartPointer<T>::getValue()
{
return *this->data;
}
template <typename T> void SmartPointer<T>::setValue(T val)
{
if(val<0)
{
throw "SmartPointer does not handle negative numbers";
}
this->data = &val;
}
int main()
{
SmartPointer<int> intOne(1);
SmartPointer<int> intTwo(3);
intTwo.setValue(10);
cout<<"intOne: "<<intOne.getValue()<<endl;
cout<<"intTwo: "<<intTwo.getValue()<<endl;
}
您的构造函数按值t值t,然后尝试将内部指针设置为该值的本地副本。它应该取为t的地址。
您的异常内容是不必要的,因为该类甚至不知道哪种类型是T,因此可能是某种类型的类型,该类型没有与INT的比较操作员。即使您确实需要抛出异常,也应该将它们捕获在main()
中,因为没有人期望构造函数将错误消息打印到屏幕上。throw "message"
是错误的,因为您正在尝试投掷const char*
实例。而是调用标准异常之一,例如throw domain_error("message")
。
使用this->
除了使键入较慢外,其他任何事情。
如果您不知道,使用endl
会冲洗缓冲区。如果您不需要,请使用' n'。
固定代码:
//#include <stdio.h> Why?
//#include <stdlib.h>
#include <iostream>
#include <exception>
using namespace std;
template<typename T>
class SmartPointer
{
public:
SmartPointer(T *in);
~SmartPointer();
T getValue();
void setValue(const T &val);
private:
T *data;
};
template<typename T> SmartPointer<T>::SmartPointer(T *in) //Moved implementation outside of class declaration
{
//Completely unnecessary exception stuff
data = in; //this-> is unnecessary
}
template<typename T> SmartPointer<T>::~SmartPointer()
{
delete data;
}
template<typename T> T SmartPointer<T>::getValue()
{
return *data;
}
template<typename T> void SmartPointer<T>::setValue(const T &val)
{
//More unnecessary exception stuff
*data = val;
}
int main()
{
SmartPointer<int> intOne(new int); //The constructor should take a pointer for the object to store instead of an value
SmartPointer<int> intTwo(new int);
intOne.setValue(1);
intTwo.setValue(10);
cout << "intOne: " << intOne.getValue() << 'n'; //endl flushes the buffer, kind of unnecessary here
cout << "intTwo: " << intTwo.getValue() << 'n'; //since it gets flushed upon the program exiting anyways
}