需要帮助实现SmartPointer

时间:2018-04-03 02:35:31

标签: c++ templates smart-pointers

我在C ++中为分配实现智能指针时遇到了麻烦。 我的代码应该创建两个SmartPointers。第一个指向1,第二个指向3,但更改为10.我的代码应打印出来

intOne:1 intTwo:10

但是打印出

intOne:10 intTwo: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 = &in;
            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;
}

1 个答案:

答案 0 :(得分:0)

构造函数采用T by值,然后尝试将内部指针设置为值的本地副本。它应该取代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
}