值初始化一个自动对象? [英] Value-initializing an automatic object?

查看:115
本文介绍了值初始化一个自动对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个模板类,并且在我的代码中,我们希望能够在栈上初始化一个参数化类型的对象。现在,我通过编写这样的东西来实现这一点:

I'm writing a template class and at one point in my code would like to be able to value-initialize an object of the parameterized type on the stack. Right now, I'm accomplishing this by writing something to this effect:

template <typename T> void MyClass<T>::doSomething() {
    T valueInitialized = T();
    /* ... */
}

(除非编译器是聪明的),它需要不必要的创建和破坏临时 T 对象。我想写的是以下,我知道是不正确的:

This code works, but (unless the compiler is smart) it requires an unnecessary creation and destruction of the temporary T object. What I'd like to write is the following, which I know is incorrect:

template <typename T> void MyClass<T>::doSomething() {
    T valueInitialized(); // WRONG: This is a prototype!
    /* ... */
}

是一种很好的方式来初始化自动对象,而不必显式构造临时对象并将其分配给自动对象。这可以做吗?

My question is whether there is a nice way to value-initialize the automatic object without having to explicitly construct a temporary object and assign it over to the automatic object. Can this be done? Or is T var = T(); as good as it gets?

推荐答案

或者 T var = T();

以下使用复制初始化,在C ++ 03代码中95%的时间可能很好:

The following uses copy-initialization, which is 'probably fine' 95% of the time in C++03 code:

T var = T();

但是对于真正的通用 C ++ 03代码, direct-initialization

But for truly generic C++03 code, you should always prefer direct-initialization:

T var((T())); // extra parentheses avoid the most vexing parse – the extra parentheses
              // force the contents to be evaluated as an expression, thus implicitly
              // *not* as a declaration.

或更好地使用 Boost Utility.ValueInit 图书馆,它包装了你的理想行为,以及各种编译器缺陷的解决方法(不幸的是,不止一个人会想到)。

Or better yet, use the Boost.Utility.ValueInit library, which packages up the ideal behavior for you along with workarounds for various compiler deficiencies (sadly, more than one might think).

对于C ++ 11,可以使用统一初始化语法以显着更少的噪声/丑陋方式实现直接的值初始化:

For C++11, one can use uniform-initialization syntax to achieve direct value-initialization in a significantly less noisy/ugly manner:

T var{}; // unambiguously value-initialization

这篇关于值初始化一个自动对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆