Showing posts with label cpp14_move. Show all posts
Showing posts with label cpp14_move. Show all posts

Dec 28, 2021

[C++] some move semantics wrap-up (interesting there's a thing i didn't realize :-) )

Reference:
The Hidden Secrets of Move Semantics - Nicolai Josuttis - CppCon 2020

https://www.youtube.com/watch?v=TFMKjL38xAI


  • const variable disables move semantics; i.e. std::move(const type); is having type of:
    const Type&& t;
    
    void take(Type&&);
    
    take(t) // invalid
  • Don't return const value from a function. This will hinder the receiver function which has the signature of:
    void take(Type &&);
    const Type getValue();
    void take(Type &&);
    
    take(getValue()); // invalid
    
  • const&& is possible, but a semantic contradiction; i.e no move constructor will take const&& type.
  • To always adopt values you can take by value and move
    If move is cheap (e.g., to init string members)
  • T&& and auto&& are universal/forwarding references
    Unless
     T is not a local function template parameter
    Unless the argument is const
    Unless T is a type expression (e.g., T::value_type)
  • std::string&& can be a universal reference in full specializations; i.e.
    template<typename T>
    void Fun(T&&);
    
    template<>
    void Fun(std::string&&); // universal reference with type std::string; NOT r-value reference.
    
  • Universal reference does not always forward
  • Getters should return by value
    or should be overloaded on reference qualifiers.
    Do NOT loop over getter return temporary object.
  • Use auto&& in a generic range-based for loop; this is due if looping over std::vector<bool> an temporary proxy object is created and auto& CANNOT bind to it.
  • The range-based for loop is broken
    when iterating over references to temporaries;
    Refer to: [C++] Object Lifetimes reading minute
  • Use std::move() for member functions that is decorated as &&(i.e. only works on r-value object)

Jul 11, 2019

[clang] Catching use-after-move bugs with Clang's consumed annotations

Reference:
https://awesomekling.github.io/Catching-use-after-move-bugs-with-Clang-consumed-annotations/

Clang9 Attributes:
https://clang.llvm.org/docs/AttributeReference.html#consumed-annotation-checking

The reason once we've defined destructor for our type compiler will not generate default move constructor/move assignment which ask the designer to explicit define those two member functions due to move semantic,  i.e what should the r-value object's data members being handled? If the data member is the resource owner , it should be nullptred(by move constructor/move assignment), which allows the type's destructor delete the nullptr(i.e a no-op).
However, if any member functions which deref the nullptred data member will crash the process at run-time.

Can this being caught at compile time in C++, like Rust did?
Clang provides “Consumed Annotation Checking”

code example:
class [[clang::consumable(unconsumed)]] CleverObject {
public:
    CleverObject() {}
    CleverObject(CleverObject&& other) { other.invalidate(); }

    [[clang::callable_when(unconsumed)]]
    void do_something() { assert(m_valid); }

private:
    [[clang::set_typestate(consumed)]]
    void invalidate() { m_valid = false; }

    bool m_valid { true };
};

int main(int, char**)
{
    CleverObject object;
    auto other = std::move(object);
    object.do_something();
    return 0;
}
Realworld Usage:
https://github.com/SerenityOS/serenity/blob/master/AK/NonnullRefPtr.h

Aug 8, 2015

[C++14] copy this ptr and RVO

Either capture this or copy *this


template <typename R, typename... Args>
auto memoize(R(*fn)(Args...))
{
    std::map<std::tuple<Args...>, R> table;
    return [fn, table](Args... args) mutable -> R {
        auto argt = std::make_tuple(args...);
        auto memoized = table.find(argt);
        if(memoized == table.end())
        {
            auto result = fn(args...);
            table[argt] = result;
            return result;
        }
        else
        {
            return memoized->second;
        }
    };
}
g++ -fno-elide-constructors

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();
}