C ++ 11 && operator (R-value reference) deprecated proxy object design template?

Scott Myers paragraph 30, “More Effective C ++,” displays a proxy object design pattern.

The problem is that you have:

X x;
x[3]=42; 
cout<<x[3]

... you need the X operator [] overload to be able to distinguish between the L value and the R value.

(maybe you need another code to run, for example, in the first case, heavy copying may be involved, but in the second case, maybe we can just pass the link).

The proxy template is that X contains the Proxy class, and X operator [] overloads an object of type Proxy.

Thus, the code will look like this:

X x;
{some Proxy object}=42; 
cout<<{some Proxy object}

Proxy "operator =", , " std::string char *", .

++ .

++ 11, ++ 11 - && & ( R).

R- L-?

-- ?

+2
1

, , .

ref , , . .

std::vector, .

:

template <typename T>
struct AutoVector
{
    std::vector<T> m_vec;
    AutoVector() { m_vec.resize(1); }

    T& operator[](const size_t index) &
    {
        std::cout << "Inside operator[" << index << "]&\n";
        if (m_vec.size() < index)
            m_vec.resize(index);
        return m_vec[index];
    }

    T operator[](const size_t index) &&
    {
        std::cout << "Inside operator[" << index << "]&&\n";
        return m_vec[index];
    }
};

, operator[] & lvalue operator[] &:

AutoVector<int> avec;
avec[4] = 6;
std::cout << avec[4] << "\n";
    --> Inside operator[4]&
    --> Inside operator[4]&
    --> 6

, operator[] && rvalue operator[] &&:

std::cout << AutoVector<int>()[0] << "\n";
    --> Inside operator[0]&&
    --> 0

. -, operator[], , rvalue , - . , .

+4

Source: https://habr.com/ru/post/1569298/


All Articles