tp.web.random_picture

2022-07-21

We are all something, but none of us are everything. — Blaise Pascal

std::atomic使用场景:多读一写

operator++重载

前置&后置

#include <cstdio>
 
class A
{
public:
    A& operator++() // ++a, pre-increment
    {
        printf("operator++()\n");
        a_++;
        return *this;
    }
    void operator++(int) // a++, post-increment
    {
        printf("operator++(int)\n");
        ++a_;
    }
private:
    int a_ = 0;
};
 
 
int main()
{
    A a;
    ++a;    // call operator++()
    a++;    // call operator++(int)
    return 0;
}

Storage duration

All objects in a program have one of the following storage durations:

  • automatic storage duration. The storage for the object is allocated at the beginning of the enclosing code block and deallocated at the end. All local objects have this storage duration, except those declared staticextern or thread_local.

  • static storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern. See Non-local variables and Static local variables for details on initialization of objects with this storage duration.

  • thread storage duration. The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration. thread_local can appear together with static or extern to adjust linkage. See Non-local variables and Static local variables for details on initialization of objects with this storage duration. (since C++11)

  • dynamic storage duration. The storage for the object is allocated and deallocated upon request by using dynamic memory allocation functions. See new-expression for details on initialization of objects with this storage duration.

The storage duration of subobjects and reference members is that of their complete object.

see also Static local variables, linkage.