'Questions about ”operator=” and ”operator[]”
I have a question about the code below.
Why is it possible to run const auto& vec1 = vec; successfully even though my_vector& operator=(const my_vector&) = delete is defined?
Secondly, why is the &, && at the end of operator[] necessary? If I remove them, I get an error.
I understand that the & after the operator is a reference to the class itself.
Then I grasp that the ones without const are for writing.
#include <iostream>
#include <stdlib.h>
#include<vector>
template<typename T, typename Alloc = std::allocator<T>>
class my_vector
{
std::vector<T, Alloc> vec;
public:
my_vector(const my_vector&);
my_vector& operator=(const my_vector&) = delete;
my_vector(std::initializer_list<T> init) : vec{init} {}
T& operator[](std::size_t n) & { std::cout<<"&"<<std::endl; return vec[n]; }
const T& operator[](std::size_t n) const& { std::cout<<"const &"<<std::endl; return vec[n]; }
T operator[](std::size_t n) && noexcept {std::cout<<"move"<<std::endl; return std::move(vec[n]); }
};
int main()
{
my_vector<int> vec{1, 2, 3};
const auto& vec1 = vec;
vec[0] = 2; //case1 &
std::cout<<vec1[0]<<std::endl;
//vec1[0] = 1; const error
int tmp1 = vec1[0] ; //case2 const&
auto&& vec5 = my_vector<int>{1, 2, 3}[0]; //case3 move
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
