initonly时间跨度场

initonly时间跨度场

本文介绍了如何正确地访问C ++ / CLI initonly时间跨度场?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code编译有警告和智能错误:

The following code compiles with warning and intellisense error:

ref class Test {
    initonly static TimeSpan Delay = TimeSpan(1,1,1);

    Test() {
        long long ticks = Delay.Ticks; // << problem
    }
};

的问题是:

  • 在警告C4395:'系统::时间跨度::蜱::获得:成员函数在initonly数据成员测试::延迟的副本,调用
  • 智能感知:服用initonly域的地址是不允许
  • warning C4395: 'System::TimeSpan::Ticks::get' : member function willbe invoked on a copy of the initonly data member 'Test::Delay'
  • IntelliSense: taking the address of an initonly field is not allowed

如何进入蜱正确?

推荐答案

嗯,这是pretty的重大失败鲸。该警告是准确的,编译器没有足够了解的时间跨度::蜱属性的getter。它不能保证吸气不会做任何可能改变结构的价值,从而将无效的 initonly 的合同。它解决它通过使结构的副本,并警告说这件事,因为这是一个可能的PERF的问题。这是一个有点笨拙,其他托管编译器进行复制,而不说任何事情。我只是花掉一个的#pragma警告(禁用:4395)。在它前面所以警告燮pressed

Well, that's pretty major fail-whale. The warning is accurate, the compiler doesn't know enough about the TimeSpan::Tick property getter. It cannot ensure that the getter doesn't do anything that might alter the value of the struct and thereby invalidates the initonly contract. It solves it by making a copy of the struct and warns about it since this is a possible perf issue. That's a bit heavy-handed, other managed compilers make the copy without saying anything about it. I'd just plunk a #pragma warning(disable:4395) ahead of it so the warning is suppressed.

只有当我尝试在VS2012将出现智能感知错误。这是一个错误。您可以在connect.microsoft.com报告。

The IntelliSense error only appears when I try this in VS2012. That's a bug. You can report it at connect.microsoft.com.

由于痛苦,而这似乎是一个私有类成员,我只是下降的 initonly 的出人头地。如果这是不可取的,那么你可以包装领域与属性,故意创建的副本,从而摆脱了这两个问题,像这样的:

Given the misery and that this appears to be a private class member, I'd just drop initonly to get ahead. If that's not desirable then you can wrap the field with a property, intentionally creating the copy, and thus get rid of both problems, like this:

ref class Test {
    initonly static TimeSpan _delay = TimeSpan(1,1,1);
    static property TimeSpan Delay {
        TimeSpan get() { return _delay; }
    }

    Test() {
        long long ticks = Delay.Ticks;
    }
};

抖动优化器将摆脱它,所以不用担心开销。

The jitter optimizer will get rid of it so don't worry about overhead.

这篇关于如何正确地访问C ++ / CLI initonly时间跨度场?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:22