简体   繁体   English

获取默认初始化(NOT值/零初始化)POD作为右值

[英]Get a default-initialized (NOT value/zero-initialized) POD as an 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 an rvalue of type A to foo() without value-initializing it? 是否可以将类型A的右值传递给foo()而不进行值初始化? Do we have to use either value-initialization or an lvalue? 我们必须使用值初始化还是左值?

What's the point of avoiding value-initialization when it "costs" no more than ten nanoseconds, you may ask. 你可能会问,当“成本”不超过10纳秒时,避免价值初始化的重点是什么。 How about a situation like this: we are hunting for a bug in an legacy app caused by an uninitialized memory access with valgrind, and zero is NOT considered as a valid value for the app. 这样的情况怎么样:我们正在寻找遗留应用程序中由于使用valgrind进行未初始化的内存访问而导致的错误,并且零不被视为应用程序的有效值。 Value initialization will prevent valgrind to spot the location of uninitialized memory access. 值初始化将阻止valgrind发现未初始化的内存访问的位置。

You may say printing an uninitialized value is an UB but my "real" use case is not limited to printing. 您可能会说打印未初始化的值是UB,但我的“真实”用例不仅限于打印。 My question should remain valid without it. 没有它,我的问题应该仍然有效。

If i understand the question correctly you need a replacement for foo(A()); 如果我正确理解了这个问题,你需要替换foo(A()); or similar cases where A() is called so that you don't have default initialization of members. 或类似的情况,其中调用A() ,以便您没有成员的默认初始化。

In that case one here is what i came up with: 在这种情况下,我想出的是:

  • First i tried to add A() = default (but this might not work with older c++ standards) and i had interesting results . 首先我尝试添加A() = default (但这可能不适用于旧的c ++标准),我得到了有趣的结果 The exact sample you provided works in reverse printing first 0 and then some random number. 您提供的确切样本首先在反向打印0,然后是一些随机数。

  • Second i did not use A() = default; 其次我没有使用A() = default; and just used a templated function 并且只使用了模板化的功能

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

    At the cost of a copy (or move) you can use it like foo(make<A>()) and get the result you wanted. 以复制(或移动)为代价,您可以像foo(make<A>())一样使用它并获得您想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM