简体   繁体   中英

pointer parameter passed by reference in a function c++

I have a class template which has a member variable std::vector<T> buffer and a member function setData , among others.

template <class T>
void ArrayT<T>::setData(const std::vector<T> * & data_ptr) {    
    buffer.assign(data_ptr->begin(), data_ptr->end());
}

I want setData to perform a deep copy of the data passed as its argument. As you can see, the argument is of type * & , which if I understand well is a pointer parameter passed by reference.

When I write:

vector<float> vec(3, 1.0);
vector<float>* vec2 = &vec;
A obj();
obj.setData(vec2);

I get an error:

E0434 a reference of type "const std::vector<float, std::allocator<float>> *&" (not const-qualified) cannot be initialized with a value of type "std::vector<float, std::allocator<float>> *"

Could someone please explain how to fix this?

The input parameter of setData() is a reference to a non-const pointer to a const std::vector . But the std::vector object you are pointing at is not const .

There is no reason to use a pointer at all in this situation. Change setData() to take the std::vector by const reference instead:

template <class T>
void ArrayT<T>::setData(const std::vector<T> &data)
{
    buffer.assign(data.begin(), data.end());
    // or simply: buffer = data;
}

vector<float> vec(3, 1.0);
Array<float> obj;
obj.setData(vec);

That being said, if you want to keep the pointer, you need to drop the const :

template <class T>
void ArrayT<T>::setData(std::vector<T> * data_ptr)
{
    buffer.assign(data_ptr->begin(), data_ptr->end());
    // or simply: buffer = *data_ptr;
}

Or at least move the const after the * to make the pointer itself const rather than the object it is pointing at:

template <class T>
void ArrayT<T>::setData(std::vector<T> * const data_ptr)
{
    buffer.assign(data_ptr->begin(), data_ptr->end());
    // or simply: buffer = *data_ptr;
}

Either way, notice I removed the reference. There is no good reason to pass a pointer by reference when you are not modifying what the pointer is pointing at. Pass the pointer by value instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM