我的问题是关于从 std 库中包装一些容器或对象,以及这样做的成本。
假设我需要创建一个 ThreadSafeStack
类。我会包装 std::stack
容器并使用互斥锁使其线程安全。这完全没问题,因为新的 ThreadSafeStack
的功能值得付出代价(函数调用)。但是,如果我想将 std::mutex
包装到类 MyMutex
中以在调试时添加日志记录功能怎么办?您认为值得还是不值得?
如果我只是为了方便而做类似的事情,以避免在我的所有文件中编写 std::
或 using::std
怎么办?你认为这是愚蠢的吗?
我已经阅读了一些关于函数调用的内容(例如 this),我认为这不会是一个很大的开销。
This would be totally ok because the functionalities of the new ThreadSafeStack would be worth the cost (function calls).
您的包装函数调用很可能会在适当的优化级别内联,从而导致零开销。例如检查 this case : 包装在 operator*
中的指针取消引用导致与原始指针取消引用相同的汇编代码。许多级别的 C++ 抽象可以在优化过程中消失。
不过,虚函数调用不太可能被内联。因此,只要有意义就使用普通函数。
But what if I want to wrap the std::mutex into a class MyMutex to add logging functionalities when debugging ?
日志记录可能会增加一些显着的成本,但如果您只在调试期间需要它 - 您可以通过 ifdef
s 或任何其他方式在发布版本中安全地禁用它,例如:
const bool do_logging = false; // somewhere
// ...
if(do_logging) // branching can be easily removed by optimizer,
// because do_logging is constant
// ...
else
// ...
In your opinion, would it be worth it or not ?
当然可以。基于标准库设施构建更有用的抽象是常见的做法。
And what if I do something like that only for convenience, to avoid writing std:: or using::std in all my files ? Do you think it is stupid ?
这取决于您的项目 - 在某些情况下甚至可以在头文件中使用 using namespace std
。但请注意 - 包含此类 header 的人可能会面临名称冲突。
在大多数情况下,可以在 .cpp
文件的头部使用 using namespace std
(在 inlucde
之后)。但即使这是 Not Acceptable ,您始终可以在函数级别使用 using
指令:
void foo()
{
using namespace std;
// ...
}