c++ - 当类用作映射值时,复制构造函数不起作用

标签 c++

我找不到比直接粘贴到此处(虽然是简化版本)更简单的方法来解释我的问题。 我有一个模板化类,其中包含必要的赋值运算符、默认构造函数和一个 common 复制构造函数。当我尝试在我的代码中使用此类时,出现如下错误:

#include<map>
#include<vector>

template<class T>
class BufferContainer
{
public:

    BufferContainer& operator=(BufferContainer& other)
    {
        buffer = other.get();
        return *this;
    }

    BufferContainer( const BufferContainer& other ) :
        buffer( other.get() )
     {
     }

    BufferContainer(){
    }

    std::vector<T>& get() {
            return buffer;
    }

    void add(T value) {

        buffer.push_back(value);
    }

    std::vector<T> buffer;
};

int main()
{
    std::map<int, BufferContainer<int> > myMap;
    myMap[1].add(1);
    return 1;
}

错误是:

Practice $ g++ template.cpp 
template.cpp: In instantiation of ‘BufferContainer<T>::BufferContainer(const BufferContainer<T>&) [with T = int; BufferContainer<T> = BufferContainer<int>]’:
/usr/include/c++/4.7/bits/stl_pair.h:105:31:   required from ‘std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = const int; _T2 = BufferContainer<int>]’
/usr/include/c++/4.7/bits/stl_map.h:458:11:   required from ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int; _Tp = BufferContainer<int>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, BufferContainer<int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = BufferContainer<int>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]’
template.cpp:38:9:   required from here
template.cpp:16:26: error: passing ‘const BufferContainer<int>’ as ‘this’ argument of ‘std::vector<T>& BufferContainer<T>::get() [with T = int]’ discards qualifiers [-fpermissive]

如果您帮助我解决此问题的方法,我将不胜感激,更重要的是,请告诉我为什么会出现此错误。 谢谢

最佳答案

您的 get() 函数不是 const 限定的,您是通过复制构造函数中对 const 的引用来调用它的:

BufferContainer( const BufferContainer& other ) :
//               ^^^^^
    buffer( other.get() )
//          ^^^^^^^^^^^
{
}

这就是编译器提示的原因。您不能通过对 const 的引用来调用非 const 函数。引用 const 意味着您不会修改引用对象的状态,因此您只能调用 promise 不修改对象状态的函数。这就是成员函数上的 const 限定符的用途 - 做出 promise 。

因此,您的成员函数 get() 应该限定为 const,并返回对 const vector 的引用:

std::vector<T> const& get() const 
//             ^^^^^        ^^^^^
{
    return buffer;
}

如果您需要非const 函数get() 因为您希望允许客户端修改内部buffer(建议:考虑这是否真的是个好主意),那么你将不得不提供 get()两个重载:

  • 一个 const 限定的返回对 const vector 的引用(如上所示)
  • 一个非 const 限定的,它返回对可修改 vector 的引用(类似于原始的 get())

关于c++ - 当类用作映射值时,复制构造函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16980447/

相关文章:

c++ - 我分配了一个指针,它自己清空了

c++ - 将 ostream 重定向到文件不起作用

c++ - 归并排序程序陷入错误

c++ - 如何初始化字符串的std::array?

c++ - C++ 中带有字符串 arg 的全局函数

c++ - 初学者练习 : Design a Money class

c++ - clock_gettime() 返回错误的结果(VirtualBox 上的 Debian wheezy)

c++ - 错误 : expected unqualified-id before ‘__extension__’ in Linux (Cent OS)

c++ - C++中未定义的类错误

c++ - 访问配置目录的跨平台方式