从非const的向量返回const向量

时间:2012-06-20 00:20:47

标签: c++ vector const shared-ptr

我正在为数据库类编写以下代码来读取文件中的数据:

typedef std::vector<char> CharVec;
typedef std::vector<const char> ConstCharVec;
typedef std::shared_ptr<CharVec> CharVecPtr;
typedef std::shared_ptr<ConstCharVec> ConstCharVecPtr;

const ConstCharVecPtr DB::readData(unsigned int amount,unsigned int offset,unsigned int flag)
{
    CharVec data;
    //Add stuff to data from the file...
    //etc...
    return ConstCharVecPtr(new ConstCharVec(data.begin(),data.end()));
}

在编译期间,return语句失败:

include\c++\bits\allocator.h|89|  required from 'class std::allocator<const char>'|
include\c++\bits\alloc_traits.h|86|  required from 'struct std::allocator_traits<std::allocator<const char> >'|
include\c++\ext\alloc_traits.h|90|  required from 'struct __gnu_cxx::__alloc_traits<std::allocator<const char> >'|
include\c++\bits\stl_vector.h|76|  required from 'struct std::_Vector_base<const char, std::allocator<const char> >'|
include\c++\bits\stl_vector.h|208|  required from 'class std::vector<const char>'|
C:\Users\Brian\work\cr\code\DB.cpp|86|  required from here|

我想维护返回值的常量,因为其他函数希望数据库中的原始数据是常量,但我看不到将非const数据转换为const。 char向量用作返回,以便原始数据的用户可以将其提供给需要const char *指针的函数。有没有办法完成这个const转换,或者我最好为这种数据使用另一种返回类型?

0 个答案:

没有答案
相关问题