简体   繁体   English

我应该在类或名称空间范围使用静态const变量吗?

[英]Should I prefer static const variables at class or namespace scope?

Does one have any tangible benefits over the other? 一个相对于另一个有什么明显的好处吗? I've started using the latter because it doesn't pollute the header file with static const declarations, so it's a bit easier to read. 我开始使用后者,因为它不会用静态const声明污染头文件,因此它读起来有点容易。 I'm often using these constants in only a couple of member functions. 我经常在几个成员函数中使用这些常量。

Class scope: 班级范围:

.hpp .HPP

class MyType 
{
private:
    static const std::wstring kFoo;
}

.cpp 的.cpp

const wstring MyType::kFoo(L"foo");
...
void MyType::parse(const wstring& input)
{
    if (input == kFoo) { do1; }  
    ...
}

versus

namespace scope 命名空间范围

.cpp 的.cpp

const wstring kFoo(L"foo");
...
void MyType::parse(const wstring& input)
{
    if (input == kFoo) { do1; }  
    ...
}

First of all, 首先,

const wstring kFoo(L"foo");

is in global scope, not in a namespace . 在全局范围内,不在namespace You can easily wrap that in an anonymous namespace . 您可以轻松地将其包装在匿名namespace

namespace
{
   const wstring kFoo(L"foo");
}

Coming to the question of whether it is better to use static member of the class or a member in a namespace , the answer depends on team coding style guidelines as well as personal preferences. 关于最好使用类的static成员还是使用namespace的成员的问题,答案取决于团队编码风格准则以及个人喜好。

My suggestion would be to put it under the anonymous namespace in the .cpp file. 我的建议是将其放在.cpp文件中的匿名namespace下。 That way, it can remain an implementation detail and the class definition is not polluted by an implementation detail. 这样,它可以保留实现细节,并且类定义不会受到实现细节的污染。

PS PS

Please note that the question static string constants in class vs namespace for constants [c++] addreses the issue but with a difference. 请注意, 类[ v ++]中的类与名称空间中的静态字符串常量问题[c ++]解决了该问题,但有所不同。 In the other post, the user wants to share the static member variable across multiple files. 在另一篇文章中,用户希望在多个文件之间共享static成员变量。 In your post you have explicitly put the static member variable as a private member, and hence not to be shared acrosss files. 在您的文章中,您已明确地将static成员变量作为private成员,因此不会在文件中共享。 If that assessment is incorrect, your question is a duplicate of the other question and deserved to be closed as such. 如果该评估是不正确的,则您的问题是另一个问题的重复,因此应同样予以解决。

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

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