Showing posts with label cpp11_r_value. Show all posts
Showing posts with label cpp11_r_value. Show all posts

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))),
    {});

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

Feb 13, 2015

[C++11] move constructor vs. move assign operator

Well, didn't differentiate this behavior difference before.

disable RVO:
-fno-elide-constructors

move constructor binds to R-value.
(includes x-value and pr-value,
test under -fno-elide-constructors enabled.)

cppref : move_constructor

Making move_constructor 'delete' will
prevent Type taking pr-value object to create the type instance,
even Type implemented copy constructor interface.

'=delete' is another usage paradigm

Type copy by value by pr-value will always never call
move-constructor, thus no side-affect, since it's optimized
directly through constructor, no need to do another useless
move construct.


move assign operator, OTOH, binds to pr-value, x-value. like other functions.

Initialize type instance with pr-value, will call default copy constructor; however, this is usually eliminated due to no bother just initialize the type instance with pr-value directly. Same idea behind function taking copy-by-value argument with pr-value will eliminate extra copy-constructor call.

Dec 1, 2014

[C++11] decltype with X-value expression

Code often shows e.g:
T& operator=(T&& rhs)
{
 var_1 = std::move(rhs.var_1);
}
What would be the difference between:
var_1 = std::move(rhs.var_1);
//and
var_1 = std::move(rhs).var_1;
Now having pr-value, x-value, g-value etc. http://en.cppreference.com/w/cpp/language/value_category

  1. r-value reference is r-value. like c.v, r-value object's data member is
    r-value. 
  2. decltype(expression) will consider
  • T l-value -> T& 
  • T x-value -> T&&
  • otherwise, T

decltype((std::move(x).var_1)) tmp_1 = 42;
has the type of type_var_1&&
decltype((Type{}.var_1)) tmp_1; //Type{} as p-rvalue
has the type of var_1 :-| code test below:
#include <iostream>
#include <utility>

using namespace std;

struct FunObj
{
    int a{0};
    int* ptr{new int{42}};
 
    auto fin()&&
    {
        cout << "~fin~" << endl;
    }

    auto& operator=(FunObj&& rhs)
    {
        cout << "in FunObj move assign op" << endl;
        a = rhs.a;
        ptr = rhs.ptr;
        rhs.ptr = nullptr;
        return *this;
    }
 
    ~FunObj()
    {
        cout << "~FunObj Outer " << endl;
        if (ptr != nullptr)
        {
            cout << "~FunObj Inner" << endl;
            delete ptr;
        }
    }
};


int main()
{
    FunObj fo;
    int i_tmp{42};
    /* won't compile due to r-value referece bind to l-value
    decltype((std::move(fo).a)) i_1 = i_tmp;
    */
    // int&&
    decltype((std::move(fo).a)) i_1 = 42;

    // int
    decltype((FunObj{}.a)) i_2;

    // int&&
    decltype((declval<FunObj>().a)) i_3 = 42;

    /*
     * xvalue:
     * http://stackoverflow.com/a/11661184
     * http://en.cppreference.com/w/cpp/language/decltype
     * http://en.cppreference.com/w/cpp/language/value_category
     */
    struct LocalType
    {
        FunObj fo_{};
        LocalType()=default;
        LocalType(LocalType&& lt)
        {
            // r-value reference bind to x-value
            fo_ = std::move(lt).fo_;
            // equal to :
            // fo_ = std::move(lt.fo_);
        }
    };

    LocalType lt_1;
    LocalType lt_2 = std::move(lt_1);

    // won't compile in clang 3.5.0
    // however, it compiles in 4.8.3 20140627 ~~
    // fo.fin();
    std::move(fo).fin();
    FunObj{}.fin();
}

Mar 15, 2014

[C++][C++11] Compiler generated implicit default copy constructor/move constructor assign/move assign op deprecated.

clang++ -std=c++11 test.cpp -Wdeprecated

if any of copy/move constructor defined:
default constructor must be defined if needed(as before)

If user defined copy constructor:
Move constructor is =delete

If user defined assign operator:
Move assign operator is =delete

If user defined move constructor:
Copy constructor is =delete
assign operator is =delete

If user defined move assign operator:
Copy constructor is =delete
assign operator is =delete

If user defined destructor:
None of the implicit copy/move constructor, assign/move assign operator is defined.
Generate warning of deprecated

Also beware of RVO(copy elision):
copy elision
Want Speed? Pass by Value.

------------------------

§12.8.32 of the C++11 standard:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.
In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later (即target) of the times when the two objects would have been destroyed without the optimization. 
This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which maybe combined to eliminate multiple copies):
  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value (return type要與function return type宣告的一致, 且無CV qualify) 
  • in a throw-expression, when the operand is the name of a non-volatile automatic object whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object 
  • when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move(傳入copy/move constructor若為temporary object, 且無CV qualify,則可omit) 
  • when the exception-declaration of an exception handler (Clause 15) declares an object of the same type (except for cv-qualification) as the exception object (15.1), the copy/move operation can be omitted by treating the exception-declaration as an alias for the exception object if the meaning of the program will be unchanged except for the execution of constructors and destructors for the object declared by the exception-declaration.
Reference:
Everything You Ever Wanted to Know About Move Semantics


Aug 29, 2012

[C++11] RVO , etc...

Article from C++Next site.
Reference :
In STL, there's predicate funtion/functor , which usually implemented as pure function

Most of these ideas above can be read from Stephan T. Lavavej(STL)'s article : Rvalue References: C++0x Features in VC10, Part 2 . Beware, in C++11, rvalue reference CANNOT reference lvalue. In STL's article, which rvalue CAN reference to lvaule is draft and NOT workable in C++11. The reason is explained as prevent accidentally modify the lvalue.