【问题标题】:Cannot use sizeof(member variable) to initialize a static const value in Visual Studio无法使用 sizeof(member variable) 在 Visual Studio 中初始化静态 const 值
【发布时间】:2018-03-14 23:37:23
【问题描述】:

我一直在使用 g++ 5.3.1 在 Fedora 23 机器上开发一个库,并使用 mingw 在 Windows 机器上成功构建它(如果需要,我可以在此处获取版本)。我今天将此代码交给了一位有兴趣使用它的同事。他尝试在 Visual Studio 2013(他选择的 IDE)中编译它,但它崩溃了。下面我创建了一个问题的 MCVE:

#include "stdafx.h"  // include this while in Visual Studio
#include <iostream>  // include when compiling with g++

class staticTest
{
public:
  staticTest() { };
  ~staticTest() { };

  unsigned myVal;

private:
  static const size_t staticLength = sizeof(myVal);  // errors in VS2013, compiles fine with g++ and mingw
  const size_t length_ = sizeof(myVal);  // compiles fine for all
};

使用g++ -Wall -Wextra -std=c++11 -c staticTest.cpp 编译时不会出现错误或警告。但是,在 Visual Studio 2013 中,我收到关于 staticLength 赋值行的以下 3 个错误:

statictest.cpp(12): error C2327: 'staticTest::myVal' : is not a type name, static, or enumerator
statictest.cpp(12): error C2065: 'myVal' : undeclared identifier
statictest.cpp(12): error C2070: 'unknown-type': illegal sizeof operand

我知道错误基本上在说什么,它在static 上下文中看不到成员变量,因此无法将sizeof 运算符应用于它。通过咬紧牙关,我同意将所有此类实例更改为static const size_t staticLength = sizeof(unsigned);,然后它就构建得很好。这个问题在另一个例子中更加复杂,我尝试在 static 函数中使用 sizeof(memberArray)sizeof(memberArray[0]) 做类似的事情。

我假设这是符合标准的,因为 g++ 喜欢它,而且我在微软编译器对标准松散之前就听说过,接受一种伪 c/c++ 语言。

  1. 这是不好的编码风格吗?我一直更喜欢使用sizeof(myVariable),因为它更易于维护(如果myVariable 的类型发生变化,则无需对sizeof 进行任何更改)。在我看来,编译器应该在编译时知道(就像 g++ 那样)myVal 的类型,而不关心它是否是类的成员。
  2. 是否有人知道在 Visual Studio 2013 中解决此问题的方法,或者此问题已在更高版本的 Visual Studio 中得到解决?对我来说真正的踢球者是 Windows mingw 编译得很好,但我的同事不会从 VS 让步,所以我在这里修改我的代码,使其不易维护,只是为了符合一个不稳定的 IDE/编译器的突发奇想。哦,他的最终可执行文件将针对 Linux 构建并在与我相同的机器上运行,因此在 VS 中构建它甚至不是必需的...... [愤怒/呕吐表情符号]

编辑 我也试过:

static const size_t staticLength = sizeof(this->myVal);

static const size_t staticLength = sizeof(staticTest::myVal);

都失败了。

【问题讨论】:

  • 至于变通方法,你试过sizeof staticTest().myVal吗?还是因为staticTest 仍然不完整而失败?
  • @melpomene 感谢您的建议,但不幸的是仍然没有好处。你猜对了,我得到的 3 个错误中的第一个是 error C2027: use of undefined type 'staticTest'
  • 如果将初始化移出类怎么办?这是允许的,对吧? class staticTest { ... static const size_t staticLength; }; const size_t staticTest::staticLength = sizeof staticTest().myVal;
  • @melpomene !!!请写一个答案,在 VS 和g++ 中为我编译!
  • "stdafx.h" 和/或 &lt;iostream&gt; 真的相关吗?

标签: c++ visual-studio-2013


【解决方案1】:

这适用于我的 Visual Studio 编译器:

static const size_t staticLength = sizeof(decltype(myVal)); 

据我所知,这应该适应对 myVal 类型的任何更改。

如果您不必在类定义中对其进行初始化,请不要在类中进行初始化并具有:

const size_t staticTest::staticLength = sizeof staticTest::myVal;

在 .cpp 文件中

【讨论】:

  • 使用 decltype 在 99% 的用例中为我解决了这个问题,static 函数中的一个不同场景除外。就我而言,MS 编译器可能会大打出手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 2011-04-18
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
相关资源
最近更新 更多