前向声明std :: string和std :: wstring [英] forward declaration of std::string and std::wstring
问题描述
经常讨论不能向前声明std :: string和std :: wstring的问题.据我了解,原因是这些类型是模板类basic_string的实例化的类型定义:
The problem of the inability to forward declare std::string and std::wstring is often discussed. As I understand, the reason is that those types are typedefing of instantiation of template class basic_string:
namespace std {
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
}
该语言不允许向前声明typedef.
And forward declaration of a typedef isn't allowed by the language.
对于使用继承而不是typedef的c ++标准,会不会更好:
Wouldn't it be better for the c++ standard using inheritance instead of typedef:
namespace std {
class string : public basic_string<char> {};
class wstring : public basic_string<wchar_t> {};
}
这样,我们就可以向前声明std :: string和std :: wstring?
So that way we could forward declare std::string and std::wstring?
推荐答案
对于使用继承而不是typedef [...]的c ++标准来说,会更好吗?
Wouldn't be better for the c++ standard using inheritance instead of typedef [...]
否.
std :: basic_string不能以任何形式继承.此限制允许实现std :: basic_string,因为它没有虚拟函数表,因此创建和销毁它的成本更低(更快).
The std::basic_string is not meant to be inherited in any form. This limitation allows the implementation of a std::basic_string, that is much cheaper (faster) to create and destroy, as it has no virtual function table.
如果需要定义std :: [w]字符串,只需#include
即可.
If you need std::[w]string to be defined, just #include
it.
编辑(回答评论)
C ++(和标准库)的指导原则之一是不要为不使用的东西付费".这意味着代码是以这样一种方式编写的,即您不必为不需要的功能招致运行时费用.
One of the guiding principles of C++ (and the standard library) is "do not pay for what you do not use". This means the code is written in such a way, that you should not incur runtime costs for features you do not need.
如果每个实例都有一个虚拟表,则创建一个std :: string实例的开销将大大增加(这将使使用std :: string的做法在性能关键的代码中望而却步.)
Creating a std::string instance would be much more expensive if each instance had a virtual table (and this would make using std::string, prohibitive in performance-critical code).
相反,std :: string旨在作为C char*
机制的快速,类型安全的RAII实现.同样,您不应尝试从std :: vector,列表,地图,shared_ptr,unique_ptr等继承.
Instead, std::string is intended as a fast, type-safe, RAII implementation of the C char*
mechanism. Similarly, you should not attempt to inherit from std::vector, list, map, shared_ptr, unique_ptr and so on.
如果您确实需要一个字符串基类,请考虑自己编写一个your_namespace::[w]string_base
(一个简单的实现就是在内部封装一个std::[w]string
的实现.)
If you really need a string base class, consider writing a your_namespace::[w]string_base
yourself (a trivial implementation would be one that encapsulates a std::[w]string
internally).
这篇关于前向声明std :: string和std :: wstring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!