不可变的全局对象应该声明为"const my_result_t BLAH"还是"extern const my_result_t BLAH;"?



首先,一些激励人心的背景信息;我正在尝试将错误代码(从函数返回(表示为超轻量级人类可读字符串而不是枚举整数的想法,如下所示:

#include <string.h>
/** Ultra-lightweight type for returning the success/error status from a function. */
class my_result_t
{
public:
/** Default constructor, creates a my_result_t indicating success */
my_result_t() : _errorString(NULL) {/* empty */}
/** Constructor for returning an error-result */
my_result_t(const char * s) : _errorString(s) {/* empty */}
/** Returns true iff the result was "success" */
bool IsOK() const {return (_errorString == NULL);}
/** Returns true iff the result was an error of some type */
bool IsError() const {return (_errorString != NULL);}
/** Return a human-readable description of the result */
const char * GetDescription() const {return _errorString ? _errorString : "Success";}
/** Returns true iff the two objects are equivalent */
bool operator ==(const my_result_t & rhs) const
{
return _errorString ? ((rhs._errorString)&&(strcmp(_errorString, rhs._errorString) == 0)) : (rhs._errorString == NULL);
}
/** Returns true iff the two objects are not equivalent */
bool operator !=(const my_result_t & rhs) const {return !(*this==rhs);}
private:
const char * _errorString;
};
my_result_t SomeFunction()
{
FILE * fp = fopen("some_file.txt", "r");
if (fp)
{
fclose(fp);
return my_result_t();  // success!
}
else return my_result_t("File not Found");
}
int main(int, char **)
{
printf("SomeFunction returned [%s]n", SomeFunction().GetDescription());
return 0;
}

。这个想法是,任何函数都不必在某处维护"官方"错误代码的集中注册表,而是可以简单地以人类可读的方式返回一个描述其特定错误条件的字符串。 自sizeof(my_result_t)==sizeof(const char *)以来,这不应该比传统的返回整数错误代码约定(例如POSIX喜欢使用(的效率低得多。 (当然,我必须小心不要返回指向临时字符缓冲区的指针(

。所有这些都相当有效;我的问题涉及后续的改进,即为某些常见的错误类型创建一些全局my_result_t定义,例如:

const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
const my_result_t RESULT_ACCESS_DENIED("Access Denied");  
const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");  
const my_result_t RESULT_FILE_NOT_FOUND("File not Found");  
[...]

。这样,SomeFunction()的作者就可以return RESULT_FILE_NOT_FOUND;,而不是被要求输入自定义错误字符串并冒错别字、与其他函数的结果字符串不一致等风险。

我的问题是,声明这些通用/全局结果代码的运行时效率最高的方法是什么?

一种方法是使它们成为"单例对象",如下所示:

// my_result_t.h  
extern const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
extern const my_result_t RESULT_ACCESS_DENIED("Access Denied");  
extern const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");  
extern const my_result_t RESULT_FILE_NOT_FOUND("File not Found");  
// my_result_t.cpp
const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
const my_result_t RESULT_ACCESS_DENIED("Access Denied");  
const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");  
const my_result_t RESULT_FILE_NOT_FOUND("File not Found");

。或者另一种方式是简单地将以下内容放在一个中央头文件中:

// my_result_t.h  
const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
const my_result_t RESULT_ACCESS_DENIED("Access Denied");  
const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");  
const my_result_t RESULT_FILE_NOT_FOUND("File not Found");  

。后一种方式似乎工作正常,但我不是 100% 确信这样做是犹太洁食;首先,这意味着例如RESULT_OUT_OF_MEMORY是每个翻译单元中的一个单独的对象,这似乎可能会给链接器带来重复数据删除的压力,甚至调用可以想象的未定义行为(我不确定一个定义规则在这里如何适用(。 另一方面,使用 "extern" 方法意味着my_result_t对象的实际内容仅在编译my_result_t.cpp时对优化器可用,而在编译引用这些对象的任何其他函数时不可用,这意味着优化器可能无法进行内联优化。

从正确性的角度来看,一种方法是否比另一种方法更好,但也有助于优化器使代码尽可能高效?

Const 命名空间范围变量应该具有默认的内部链接,因此在标头中写入const my_result_t RESULT_XXX;是正确的:

用于

声明非局部非易失性的 const 限定符 非模板非内联变量,即 未声明的外部给它内部链接。这与 C 其中 const 文件范围变量具有外部链接。

此外,在函数中使用外部符号很可能不会阻止它进行内联优化,因为编译器会将函数解压缩到位,以原样保留任何外部符号。然后,链接器解析这些符号。但是,编译器的实现可能会有所不同,因此对此没有明确的说法。也就是说,使用extern const很可能不会给内联优化带来任何麻烦。(我尝试使用 msvc,用__inline关键字内联提示,发出的程序集显示SomeFunction()内联(。

我建议使用extern const方法,因为每个结果对象只有一个实例。

下面是我的原始答案,如果您使用 c++ 17,这很好(使用extern const您必须编写两次内容:定义然后声明,但如果您使用inline变量,则不然(


C++ 17 附带了一些您需要的功能。本质上,我们可以用string_viewconstexprinline变量构建my_result_t类。我已经对您的代码进行了一些修改:

// ErrorCode.h
#pragma once
#include <string_view>
/** Ultra-lightweight type for returning the success/error status from a function. */
class my_result_t
{
public:
/** Default constructor, creates a my_result_t indicating success */
constexpr my_result_t() : _errorString{} {/* empty */ }
/** Constructor for returning an error-result */
constexpr my_result_t(const char* s) : _errorString(s) {/* empty */ }
/** Returns true iff the result was "success" */
constexpr bool IsOK() const { return (_errorString.data() == nullptr); }
/** Returns true iff the result was an error of some type */
constexpr bool IsError() const { return (_errorString.data() != nullptr); }
/** Return a human-readable description of the result */
constexpr std::string_view GetDescription() const { return _errorString.data() ? _errorString : "Success"; }
/** Returns true iff the two objects are equivalent */
constexpr bool operator ==(const my_result_t& rhs) const
{
return _errorString.data() ? ((rhs._errorString.data()) && 
(_errorString == rhs._errorString)) : (rhs._errorString.data() == nullptr);
}
/** Returns true iff the two objects are not equivalent */
constexpr bool operator !=(const my_result_t& rhs) const { return !(*this == rhs); }
private:
std::string_view _errorString;
};
inline constexpr my_result_t RESULT_SUCCESS{};
inline constexpr my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
inline constexpr my_result_t RESULT_ACCESS_DENIED("Access Denied");
inline constexpr my_result_t RESULT_BAD_ARGUMENT("Bad Argument");
inline constexpr my_result_t RESULT_FILE_NOT_FOUND("File not Found");
// main.cpp
#include "ErrorCode.h"
#include <iostream>
inline my_result_t SomeFunction()
{
FILE* fp = fopen("some_file.txt", "r");
if (fp)
{
fclose(fp);
return RESULT_SUCCESS;  // success!
}
else return RESULT_FILE_NOT_FOUND;
}
int main() {
std::cout << SomeFunction().GetDescription();
return 0;
}

编译器资源管理器链接

在代码中,每个翻译单元共享相同的结果对象,因为:

具有外部链接的内联函数或变量 (例如,未声明为静态(具有以下附加属性:

1( 它必须在每个翻译单元中内联声明。

2(它在每个翻译单元中都有相同的地址。

它不会影响使用对象的函数内联,因为它们本质上只是编译时间常量!

唯一的缺点是string_view大小更大(大约是常量字符指针的两倍,具体取决于实现(。但是,这可以通过实现constexpr"strcmp"函数来避免:

constexpr bool strings_equal(char const* a, char const* b) {
return a == nullptr ? (b == nullptr) : (b != nullptr && std::string_view(a) == b);
}

然后,您可以在结果类中愉快地使用const char *而不是string_view

最新更新