Get default initialized (NOT value / zero-initialized) POD as rvalue

#include <iostream>

struct A {
    int x;
};

void foo(A a) {
    std::cout << a.x << std::endl;
}

int main() {
    A a;
    foo(a);  // -7159156; a was default-initialized
    foo(A());  // 0; a was value-initialized
}

Is it possible to pass a value of r type Ato foo()without initializing the value? Do I need to use either value initialization or lvalue?

What is the point of avoiding the initialization of value when it "costs" no more than ten nanoseconds, you can ask. How about a situation like this: we are hunting for an error in an outdated application caused by uninitialized memory access with valgrind, and zero is NOT considered a valid value for the application. Initializing a value will prevent valgrind from locating uninitialized memory access.

, - UB, "" . .

+4
1

, foo(A()); , A() , .

:

  • A() = default ( ++), . , , 0, .

  • -, A() = default;

    template <class T> T make() { T tmp; return tmp; }
    

    ( ) foo(make<A>()) .

+1

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


All Articles