首页 > 解决方案 > 我真的不明白为什么在创建模板类共享指针时出现错误

问题描述

我不明白我收到的错误消息,我不知道如何解决;

template<typename T>
class shared_pointer
{
    private:
        static int howManyObjects;
        T* pointer;
    public:
        shared_pointer( T* p=nullptr)
        {
            pointer=p;
        }
        shared_pointer( shared_pointer& a)
        {
            a.pointer=this->pointer;
            howManyObjects++;
        }
        ~shared_pointer()
        {
            if(howManyObjects==1) delete pointer;
        }

        T& operator *()
        {
            return *pointer;
        }
        T* operator ->()
        {
            return pointer;
        }
};
template<typename T>
int shared_pointer<T>::howManyObjects=0;

int main()
{
    int b=5;
    int* wsk=&b;
    shared_pointer<int> a= shared_pointer<int>(wsk);
    return 0;
}

错误信息:

main.cpp: In function ‘int main()’:
main.cpp:10:25: error: cannot bind non-const lvalue reference of type ‘shared_pointer<int>&’ to an rvalue of type ‘shared_pointer<int>’
  shared_pointer<int> a= shared_pointer<int>(wsk);

In file included from main.cpp:2:0:
smartpp.cpp:14:2: note:   initializing argument 1 of ‘shared_pointer<T>::shared_pointer(shared_pointer<T>&) [with T = int]’
  shared_pointer( shared_pointer& a)

标签: c++pointers

解决方案


您的问题出在复制构造函数中:

shared_pointer( shared_pointer& a)
{
    a.pointer = this->pointer;
    howManyObjects++;
}

所以,根据参数a的类型前面的空格,你可能知道它必须是复制构造函数规则的const。但是,当您尝试将 a 放在那里时,会出现const以下错误:

shared_pointer(const shared_pointer& a)
{
    a.pointer = this->pointer; // Compilation error: assignment of member ‘shared_pointer<int>::pointer’ in read-only object
    howManyObjects++;
}

因此,您尝试删除const并收到您在帖子中显示的错误。问题不在于您试图放在那里的 const ,而是分配方向。您不想修改参数值,而是修改当前对象值。将您的复制构造函数更改为以下内容,一切都会好起来的:

shared_pointer(const shared_pointer& a)
{
    this->pointer = a.pointer; // Pay attention that this get the value of a, and not the opposite.
    howManyObjects++;
}

推荐阅读