Showing posts with label cpp11_l_value. Show all posts
Showing posts with label cpp11_l_value. Show all posts

Dec 17, 2023

[C++] all expressions that are references to functions are lvalues

A special rule in the C++ standard states that all expressions that are references to functions are lvalues.

Thus we can bind a non-const lvalue reference to a function marked with std::move() because a function marked with std::move() is still an lvalue.

Reference:

Special Rule for Casting to Rvalue References to Functions: 

The C++ standard has a specific rule regarding the value category of a cast expression when the target type is an rvalue reference to a function type. According to the standard, a cast expression to an lvalue reference type or an rvalue reference to a function type results in an lvalue.

This is a key exception to the general rule that casting to an rvalue reference to an object type yields an xvalue.

Why this special rule?

The concept of "moving" is primarily applicable to objects that own resources (like dynamic memory). Moving an object involves transferring ownership of these resources from one object to another, often leaving the source object in a valid but empty or default state. This is a meaningful operation for objects where copying is expensive.

Functions, on the other hand, do not own such resources that can be transferred in this manner. A function's identity is its entry point in memory, which is fixed. There's no state within a function itself that can be "moved" to another location or entity in the way an object's data members might be.

Therefore, casting a function to an rvalue reference to a function doesn't enable any form of resource transfer or change the fundamental lvalue nature of the function itself. The C++ standard reflects this by specifying that such a cast still results in an lvalue. The expression still refers to the same identifiable function entity.
 

void f(int) {}

void(&fref1)(int) = f; // fref1 is an lvalue
void(&&fref2)(int) = f; // fref2 is also an lvalue

auto& ar = std::move(f); // OK: ar is lvalue of type void(&)(int)

Jul 15, 2017

[C++] unnamed variable

Reference:
https://www.reddit.com/r/cpp/comments/6mzxsf/c_unnamed_programming/
http://nosubstance.me/post/cpp-unnamed-programming/
https://cplusplus.github.io/EWG/ewg-active.html#35
https://github.com/jeaye/value-category-cheatsheet/blob/master/value-category-cheatsheet.pdf
http://en.cppreference.com/w/cpp/language/reference_initialization#Lifetime_of_a_temporary
https://stackoverflow.com/questions/39279074/what-does-the-void-in-decltypevoid-mean-exactly


Unnamed variable.
Used for, i.e,
    std::lock_guard
    constructor that takes only l-value but no r-value. (i.e, an unnamed pr-value object can't be used)


First attempt:
    Evaluation order is NOT guaranteed.

#include <mutex>

namespace detail {
    template<typename First>
    decltype(auto) select_last(First& first) {
        return first;
    }

    // Returns a lvalue reference to the last element.
    template<typename First, typename... Rest>
    decltype(auto) select_last(First&, Rest&... rest) {
        return select_last(rest...);
    }
}

// Takes a number of arguments and invokes the last one as a function.
// Ignores all other arguments.
template<typename... T>
void with(T&&... objects) {
    auto& fn = detail::select_last(objects...);
    fn();
}

int g_i = 0;
std::mutex g_mutex;

int main() {
    with(std::lock_guard<std::mutex>(g_mutex),
        [&]() {
            ++g_i;
        }
    );
} 

Thus, second attempt:
    Using , operator

void safe_increment() {
    std::lock_guard<std::mutex>{g_i_mutex}, ++g_i;
}

Using void type constructor to avoid user defined type , operator overload.
i.e, void() type instance is a void object.
what-does-the-void-in-decltypevoid-mean-exactly

void(UDT("1")), void(UDT("2")), [] {
    cout << "hello" << endl;
}();

Make a pr-value object a l-value:
    Be aware that the pr-value will dangle after complete the function call expression.
 
    Initializing the parameter of type int&& a temporary object of value 42 is created ([dcl.init.ref]/(5.2.2.2)),
    the temporary object persists until the completion of the full-expression containing the call ([class.temporary]/(5.2)).

template <typename T>
constexpr T& lvalue(T &&r) noexcept { return r; }  // return l-value

usage:

vector<char> data(
    istreambuf_iterator<char>(lvalue(ifstream("file.dat", ios::binary))),
    {});

Jul 11, 2017

[C++] char string literal is l-value

Why are string literals l-value while all other literals are r-value?

C++03 5.1 Primary expressions
§2:
A literal is a primary expression. Its type depends on its form (2.13). A string literal is an lvalue; all other literals are rvalues.

Sep 29, 2016

[C++11] shared_ptr alias constructor

std::shared_ptr's secret constructor


struct X{
    Y y;
};


struct do_nothing_deleter{
    template<typename> void operator()(T*){}
};


void store_for_later(std::shared_ptr<Y>);


void foo(){
    std::shared_ptr<X> px(std::make_shared<X>());
    std::shared_ptr<Y> py(&px->y,do_nothing_deleter());
    store_for_later(py);
} // our X object is destroyed, BAD!
void bar(){
    std::shared_ptr<X> px(std::make_shared<X>());
    std::shared_ptr<Y> py(px,&px->y);
    store_for_later(py);
} // our X object is kept alive, i.e px NEVER destroyed even out of scope.


struct X2{
    std::unique_ptr<Y> y;
    X2():y(new Y){}
};


void baz(){
    std::shared_ptr<X2> px(std::make_shared<X2>());
    std::shared_ptr<Y> py(px,px->y.get());
    store_for_later(py);
} // our X2 object is kept alive, DITTO
aa as

http://stackoverflow.com/a/27109774/1316609
However, r-reference to prvalue's data member will exist
even the prvalue destructs the internal data member(i.e r-reference make a copy out of it),
same as const T&.

For const T& to a l-value data member, the destruct of internal data member will
effect the outer const T&, this is by standard.
http://stackoverflow.com/a/3097861