Python报错:AttributeError: type object 'str' has no attribute '_name_'(机器学习实战treePlotter代码)解决方案
最新推荐文章于 2023-04-04 04:00:00 发布
最新推荐文章于 2023-04-04 04:00:00 发布
25229
学习《机器学习实战》这本书时,按照书上的代码运行,产生了错误,但是在代码中没有错误提示,产生错误的代码如下:
if type(secondDict[key])._name_ == 'dict':
报错如下:
首先我们先看一下报错:
AttributeError: type object 'str' has no attribute '_name_'
翻译过来是:
属性错误:类型对象“ str ”没有属性“_name_”,
错误产生是因为版本不同,作者使用的是2.x版本,而我使用的是3.6版本。
Python3中类型对象“ str ”没有“_name_”属性,所以我们需要将属性去掉。除此之外,这句判断的语句本来是判断该节点类型是否为dict(字典),但是因为加上了单引号(‘’),就变成字符串了,这样会产生其他错误,所以我们也需要将单引号去掉。
所以,将代码改为如下即可:
if type(secondDict[key]) == dict:
然后运行就可以啦!
Python报错:AttributeError: type object 'str' has no attribute '_name_'(机器学习实战treePlotter代码)解决方案
报错信息学习《机器学习实战》这本书时,按照书上的代码运行,产生了错误,但是在代码中没有错误提示,产生错误的代码如下:if type(secondDict[key])._name_ == 'dict':报错如下:错误原因首先我们先看一下报错:AttributeError: type object 'str' has no attribute '_name_'翻译...
在运行嵩天老师
python
爬虫课中单元6中的实例“中国大学排名爬虫”会出现如下图
错误
:
AttributeError
: ‘None
Type
’
object
has no
attribute
‘children’
意思是 ‘None
Type
’ 对象没有
属性
‘children’ ,这个
错误
说明’children’
属性
的对象 soup 是一个空类型,那就意味着soup = BeautifulSoup(html,‘html.parser’)中soup并没有得到解析出来的html页面,那就是说在调用getHTMLText(url)函数时这个函数并没有得到url链接对应的网页信息。
错误
就出在get
在做《Machine Learning in Action》书中的第三章绘制树形图时遇到了这个问题
AttributeError
:
type
object
'
str
' has no
attribute
'_name_'
很明显是if
type
(secondDict[key])._name_ == ‘dict’:这一句有问题,在
python
3中并没有
type
(secondDict[key])._n
关于
AttributeError
:
type
object
‘XXXXXX’ has no
attribute
'name’的
报错
的原因,先运行运行一段
代码
class Person(
object
):
def __init__(self,name):
self.name=name
def play(self):
print('工作')
if __name__ == '__main__':
p=Person('KB')
p.play
imgName=‘E:\AndroidWork\Bird_Identification_App-mas
ter
\Bird_Identification_Server\mask_rcnn-mas
ter
\images\cars.jpg’
出错版:args[‘image’]=imgName
修改版:args[‘image’]=Path(imgName)
用于:log.info(‘Start R-CNN M...
一年前用flask框架开发了一个后台管理系统,最近想在某个新增和修改页面增加一个上传附件的功能,由于常见没用,基本忘的差不多了,花了2个小时解决了问题。
要加字段就需要改动以下四个地方:
1.models.py中增加对应表的字段
2.form.py表单中新增要加的上传附件的字段
3.静态文件(新增和修改页面)html中增加需要的字段
4.逻辑文件.py中针对新增和修改提交的更新
pycharm中更新数据库字段时操作:
1.删除migrations文件夹,删除数据库中alembic_versio
enc
type
属性
enc
type
这个
属性
管理的是表单的MIME(Multipurpose In
ter
net Mail Extensions)编码,共有三个值可选:
1、application/x-www-form-urlencoded —默认值,作用是设置表单传输的编码,不能用于上传文件
eg: AJAX中xmlHttp.setRequestHeader(“Content-
Type
”,“application/x-www-form- urlencoded”),
share=0
buyTime=datetime.
str
pdatetime('2018-08-18','%Y-%m-%d')
sellTime=datetime.
str
pdatetime('2018-08-19','%Y-%m-%d')
def __init__(...
Tips and Tricks In
ter
net Development Index
--------------------------------------------------------------------------------
As with any
type
of programming, writing bug-free, efficient scripts that meet your expectations takes a bit of work. The following sections provide some tips and hints to make that work take less time and go more smoothly.
Checking the In
ter
net Explorer Version Number
Canceling a Button Click
Preventing a Document From Being Cached
Using
Object
s
Replacing Custom Controls with DHTML
Checking the In
ter
net Explorer Version Number
You should always check for the
type
and version of the client browser, so that your content degrades gracefully if the client browser does not support features on your Web site.
The easiest way to identify a browser and its charac
ter
istics (browser code name, version number, language, etc.) in script is through the Dynamic HTML (DHTML)?A HREF="
object
s/obj_navigator.html">navigator
object
. You can also access this
object
and its properties in C++ applications through the IOmNavigator in
ter
face.
The userAgent property of the navigator
object
returns a
str
ing that includes the browser and browser version. The following example Microsoft® JScript® function runs on most browsers and returns the version number for any Microsoft In
ter
net Explorer browser and zero for all other browsers.
SHOWExample
function msieversion()
// Return Microsoft In
ter
net Explorer (major) version number, or 0 for others.
// This function works by finding the "MSIE "
str
ing and extracting the version number
// following the space, up to the semicolon
var ua = window.navigator.userAgent
var msie = ua.indexOf ( "MSIE " )
if ( msie > 0 ) // is Microsoft In
ter
net Explorer; return version number
return parseFloat ( ua.sub
str
ing ( msie+5, ua.indexOf ( ";", msie ) ) )
return 0 // is other browser
When checking browser version numbers, always check for version numbers grea
ter
than or equal to a target version. In this way, your Web site will be be compatible with future versions of the browser. For example, if you have designed your content for the latest version of In
ter
net Explorer, use that version number as a minimum version number.
Note Browsers often have several releases of a browser version. For example, 4.01, 5.0, 5.5 and 6.0b are all different versions of In
ter
net Explorer. The 'b' in 6.0b represents a beta version of In
ter
net Explorer 6.
As of In
ter
net Explorer 5, conditional comments are available as an al
ter
native technique for detecting browser versions. Conditional comments have the advantage of not using a script block, which means that it is not always necessary to use scripting and DHTML when working with conditional comments. When no scripting is used in a Web page, no scripting engine needs to be loaded. Conditional comments are processed during the downloading and parsing phase, so only the content that is targeted for the browser loading the Web page is actually downloaded. Conditional comments can be combined freely with other browser detection techniques. For more information, see About Conditional Comments.
Canceling a Button Click
The following HTML example shows a common scripting mistake related to event handling and canceling the default action.
SHOWExample
<HEAD><TITLE>Canceling the Default Action</TITLE>
<SCRIPT LANGUAGE="JScript">
function askConfirm()
{ return window.confirm ("Choose OK to follow hyperlink, Cancel to
not.")
</SCRIPT>
<BODYonload="b3.onclick=askConfirm">
<!-- Try links with different hookups - should be canceled by "Cancel" to confirm dialog. -->
<BR><A NAME=b1 HREF="http://www.microsoft.com" onclick="askConfirm()">1 Without return (won't work)</A>
<BR><A NAME=b2 HREF="http://www.microsoft.com" onclick="return askConfirm()">2 With return (works)</A>
<BR><A NAME=b3 HREF="http://www.microsoft.com">3 Function poin
ter
(works)</A>
</BODY>
</HTML>
The first a element in this example does not work properly. Without the return in the onclick燡Script expression, the browser in
ter
prets the function expression, throws away the resulting value, and leaves the default action unaffected.
The other a elements correctly bind the return value to the event, hence the default action can be canceled when false is returned.
Preventing a Document From Being Cached
You can prevent a document from being cached by adding the following meta tag to the document.
<META HTTP-EQUIV="Expires" CONTENT="0">
Preventing the document from being cached ensures that a fresh copy of the document will always be retrieved from the site, even during the user's current session, regardless of how the user has set the browser's caching options. This is useful if the content of the document changes frequently.
Using
Object
s
Object
s are Microsoft® ActiveX® Controls or other similar components that provide custom capabilities and services for HTML documents. You can add a control to your document using the
object
element, and you can gain access to the capabilities and services of the control using its properties and methods from script.
When using
object
s, be aware that DHTML extends every
object
by providing these additional properties:
align classid code
codeBase code
Type
data form
height name
object
recordset
type
width
If a control has properties with these same names, you will not be able to access the properties unless you preface the name with the
object
property. For example, assume that an ActiveX control is added to the document using the following:
<
OBJECT
ID="MyControl" HEIGHT=100 WIDTH=200 CLASSID="clsid: ... ">
</PARAM NAME="width" VALUE="400">
</
OBJECT
>
In this example, there are two widths: an extended property set within the
object
element, and a property belonging to the control that is set using the param element. To access these from script, you use the following code.
alert(MyControl.width); // this is Dynamic HTML's property; displays "200"
alert(MyControl.
object
.width); // this is the
object
's property; displays "400"
Replacing Custom Controls with DHTML
DHTML provides everything you need to generate animated effects without resorting to custom controls. For example, consider the following script, which is a replacement for the Path control.
SHOWExample
var tickDuration;
tickDuration = 50;
var active
Object
Count;
var active
Object
s;
var itemDeactivated;
var tickGeneration;
active
Object
s = new Array();
active
Object
Count = 0;
timerRefcount = 0;
itemDeactivated = false;
tickGeneration = 0;
function initializePath(e) {
e.waypointX = new Array();
e.waypointY = new Array();
e.duration = new Array();
function addWaypoint(e, number, x, y, duration) {
e.waypointX[number] = x;
e.waypointY[number] = y;
e.duration[number] = duration;
function compact() {
var i, n, c;
n = new Array();
c = 0;
itemDeactivated = false;
for (i=0; i<active
Object
Count; i++) {
if (active
Object
s[i].active == true) {
n[c] = active
Object
s[i];
active
Object
s = n;
active
Object
Count = c;
function tick(generation) {
if (generation < tickGeneration) {
// alert("Error "+generation);
return;
//alert("tick: "+generation);
if (itemDeactivated)
compact();
if (active
Object
Count == 0) {
return;
else {
for (i=0; i<active
Object
Count; i++) {
moveElement(active
Object
s[i]);
window.setTimeout("tick("+generation+");", tickDuration);
function start(e) {
if (itemDeactivated)
compact();
active
Object
s[active
Object
Count] = e;
active
Object
Count++;
if (active
Object
Count == 1) {
tickGeneration++;
tick(tickGeneration);
function runWaypoint(e, startPoint, endPoint) {
var startX, startY, endX, endY, duration;
if (e.waypointX == null)
return;
startX = e.waypointX[startPoint];
startY = e.waypointY[startPoint];
endX = e.waypointX[endPoint];
endY = e.waypointY[endPoint];
duration = e.duration[endPoint];
e.ticks = duration / tickDuration;
e.endPoint = endPoint;
e.active = true;
e.currTick = 0;
e.dx = (endX - startX) / e.ticks;
e.dy = (endY - startY) / e.ticks;
e.style.posLeft = startX;
e.style.posTop = startY;
start(e);
function moveElement(e) {
e.style.posLeft += e.dx;
e.style.posTop += e.dy;
e.currTick++;
if (e.currTick > e.ticks) {
e.active = false;
itemDeactivated = true;
if (e.onpathcomplete != null) {
window.pathElement = e;
e.onpathcomplete()
To use this script in your document, do the following:
Load the script using the src
attribute
of the script element.
Initialize the paths using the initializePath function.
Set the way points using the addWaypoint function.
Set the path-complete handlers using the runWaypoint function.
The following sample document shows how this works.
SHOWExample
<div id=Item1 style="position: absolute; left: 0; top: 0;">Item1</div>
<div id=Item2 style="position: absolute; left: 0; top: 0;">Item2</div>
<div id=Item3 style="position: absolute; left: 0; top: 0;">Item3</div>
<div id=Item4 style="position: absolute; left: 0; top: 0;">Item4</div>
<div id=Item5 style="position: absolute; left: 0; top: 0;">Item5</div>
<div id=Item6 style="position: absolute; left: 0; top: 0;">Item6</div>
<input
type
=button value="Start" onclick="runWaypoint(Item1, 0, 1); runWaypoint(Item2, 0, 1);">
<div id=Debug>Generation</div>
<script src="htmlpath.js">
</script>
<script>
// need to call initializePath on all
object
s that will be moved with this mechanism
initializePath(Item1);
initializePath(Item2);
initializePath(Item3);
initializePath(Item4);
initializePath(Item5);
initializePath(Item6);
// the 0th waypoint is the initial position for waypoint #1
// syntax is item, waypoint, endx, endy, duration in msecs
addWaypoint(Item1, 0, 0, 0, 0);
addWaypoint(Item1, 1, 200, 200, 2000);
addWaypoint(Item2, 0, 100, 100, 0);
addWaypoint(Item2, 1, 400, 100, 4000);
addWaypoint(Item3, 0, 400, 400, 0);
addWaypoint(Item3, 1, 200, 100, 1000);
addWaypoint(Item4, 0, 0, 0, 0);
addWaypoint(Item4, 1, 200, 200, 2000);
addWaypoint(Item5, 0, 100, 100, 0);
addWaypoint(Item5, 1, 400, 100, 4000);
addWaypoint(Item6, 0, 400, 400, 0);
addWaypoint(Item6, 1, 200, 100, 1000);
function endfunction() {
// syntax for runWaypoint is Item, start point, end point
runWaypoint(Item3, 0, 1);
runWaypoint(Item4, 0, 1);
runWaypoint(Item5, 0, 1);
runWaypoint(Item6, 0, 1);
function endfunction2() {
runWaypoint(Item1, 0, 1);
Item1.onpathcomplete = endfunction;
Item6.onpathcomplete = endfunction2;
</script>
</body>
</html>
Show Me
Fa
stR
eport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持Delphi 4-XE5 and C++Builder 6-XE5.
D2010以上版本(D14_D19)安装必读
delphi2010以上版本(D14_D19)使用者安装时,请将res\frccD14_D19.exe更名名为frcc.exe
frccD14_D19.exe是专门的delphi2010以上版本(D14_D19)编码器。其他低delphi版本,请使用frcc.exe
Fa
stR
eport® VCL is an add-on component that allows your application to generate reports quickly and efficiently. Fa
stR
eport® provides all the tools necessary for developing reports, including a visual report designer, a reporting core, and a preview window. It can be used in Embarcadero (ex Borland and CodeGear) Delphi 4-XE5 and C++Builder 6-XE5.
version 4.15
---------------
+ Added Embarcadero RAD Studio XE5 support
+ Added In
ter
nal components for FireDac database engine
+ fixed bug with images in PDF export for OSX viewers
+ Added ability to set font charset to default in Style Editor
- fixed duplex problem when printing several copies of the report
- fixed problem with PNG images
- fixed problem with TfrxPictureView transparent
version 4.14
---------------
+ Added Embarcadero RAD Studio XE4 support
- [Lazarus] fixed bug with text output
- [Lazarus] fixed bug with some visual controls in designer
- [Lazarus] improved in
ter
face of the report preview and designer
- [Lazarus] fixed bug with boolean propertyes in script code and expressions
- fixed bug with endless loop in TfrxRichView
- fixed bug with Unicode in TfrxMemoView appeared in previous release
- improved MAPI in
ter
face in TfrxExportMail export
- fixed some problems with allpication styles XE2/XE3
- improved compatibility with Fast Report FMX
version 4.13
---------------
+ Added Lazarus Beta support starts from Fast Report Professionnal edition. Current version allows preview, print and design report template under Windows and Linux platform (qt).
+ Added Embarcadero RAD Studio XE3 support
- fixed compatibility with Fast Report FMX installed in the same IDE. This version can co exist with Fast Report FMX version at the same time.
+ published "Quality" property of TfrxPDFExport
object
+ published "UseMAPI" property of TfrxExportMail
object
+ published "Picture
Type
" property to ODF export
- fixed bug with expressions in RichEdit
- fixed bug in multi-column reports
- fixed exception in the report designer
- fixed bug with URLs in Open Document Text and Open Document Spreadsheet exports
- fixed format
str
ing in XLS OLE export
- fixed format
str
ing in XLS BIFF8 export
- fixed output of the check boxes on the highlighted lines in PDF export
- fixed bug with PDF anchors
- fixed bug when using two or more macroses in memo
version 4.12
---------------
+ added support of Embarcadero Rad Studio EX2 (x32/x64)
+ added export of Excel formulas in the BIFF export
+ added export of ex
ter
nal URLs in the PDF export
+ added conver
ter
from Rave Reports Conver
ter
RR2FR.pas
+ added Cross.KeepRowsTogether property
+ optimised merging cells in the BIFF export
+ added property DataOnly to exports
+ pictures format in all exports switched to PNG
+ improved number formats processing in the BIFF export
+ added property DataOnly to exports
+ added property TfrxODFExport.SingleSheet
+ added property TfrxSimpleTextExport.DeleteEmptyColumns
+ added property TfrxBIFFExport.DeleteEmptyRows
+ added progress bar to the BIFF export
- fixed bug with frame for some barcode
type
s
- fixed wrong metafiles size in the EMF export
- fixed processing of negative numbers in the OLE export
- fixed bug in handling exceptions in the OLE export
- fixed bug in creation of the progress bar (applicable to many exports)
- fixed bug in the ODF export in
str
ings processing
- fixed bug in the OLE export in numbers formatting
- fixed bug in the PDF export in rotating texts 90, 180 and 270 degrees
- fixed bug in the ODF export in processing of headers and foo
ter
s
- fixed bug in the Text export in computing
object
bounds
- fixed bug in the ODF export in UTF8 encoding
- fixed hiding gridlines around nonempty cells in the BIFF export
- fixed images bluring when exporting
- fixed word wrapping in the Excel XML export
version 4.11
---------------
+ added BIFF8 XLS export fil
ter
+ added to ODF export the Language property
+ [en
ter
prise] added "scripts" folder for additional units ("uses" directive in report script)
+ [en
ter
prise] added logs for scheduler (add info in scheduler.log)
+ [en
ter
prise] added property "Reports" - "Scripts" in server configuration - set the path for "uses" directive in report script
+ [en
ter
prise] added property "Http" - "MaxSessions" in server configuration - set the limit of maximum session threads, set 0 for unlimit
+ [en
ter
prise] added property "Reports" - "MaxReports" in server configuration - set the limit of maximum report threads, set 0 for unlimit
+ [en
ter
prise] added property "Logs" - "SchedulerLog" in server configuration - set the scheduler log file name
+ [en
ter
prise] added property "Scheduler" - "Active" in server configuration - enable of scheduler
+ [en
ter
prise] added property "Scheduler" - "Debug" in server configuration - enable writing of debug info in scheduler log
+ [en
ter
prise] added property "Scheduler" - "StudioPath" in server configuration - set the path to Fa
stR
eport Studio, leave blank for default
- [en
ter
prise] fixed bug with MIME
type
s in http header (content-
type
)
- [en
ter
prise] fixed bug with default configuration (with missed config.xml)
- [en
ter
prise] fixed bug with error pages
- fixed bug in XML export with the ShowProgress property
- fixed bug in RTF export with font size in empty cells
- fixed bug in ODF export with UTF8 encoding of the Creator field
- fixed bug in XML export with processing special charac
ter
s in
str
ings
- fixed bug in ODF export with properties table:number-columns-spanned, table:number-rows-spanned
- fixed bug in ODF export with the background clNone color
- fixed bug in ODF export with a style of table:covered-table-cell
- fixed bug in ODF export with table:covered-table-cell duplicates
- fixed bug in ODF export with excessive text:p inside table:covered-table-cell
- fixed bug in ODF export with language styles
- fixed bug in ODF export with spaces and tab symbols
- fixed bug in ODF export with styles of number cells
- fixed bug in ODF export with the background picture
- fixed bug in ODF export with charspacing
- fixed bug in ODF export with number formatting
- fixed bug in ODF export with table-row tag
- fixed bug in XLS(OLE) export with numbers formatting
- fixed bug in RTF export with processing RTF fields
- fixed bug with processing special symbols in HTML Export
- fixed bug with UTF8 encoding in ODF export
- fixed bug in PDF export with underlined,
str
uck-out and rotated texts
version 4.10
---------------
+ added support of Embarcadero Rad Studio XE (Delphi EX/C++Builder EX)
+ added support of TeeChart 2010 packages (new series
type
aren't support in this release)
+ added a property TruncateLongTexts to the XLS OLE export that allows to disable truncating texts longer than a specified limit
+ added option EmbedProt which allows to disable embedding fonts into an encrypted PDF file
+ added TfrxDateEditControl.WeekNumbers property
- fixed bug in XML and PDF exports with Korean charmap
- fixed bug in the XLS XML export about
str
iked-out texts
- fixed bug about exporting an empty page via the XLS OLE export
- fixed bug in the PDF export about coloring the background of pages
- fixed bug in embedded designer when using break point in script
- fixed bug with lost of focus in font size combo-box in designer
- fixed bug with truncate of font size combo-box in Windows Vista/7 in designer (lost of vertical scroll bar)
- fixed bug when lost file name in inherited report
- fixed bug in multi-page report with EndlessHeight/EndlessWidth
- fixed bug wit TfrxHeader.ReprintOnNewpage and KeepTogether
- fixed bug in multi-column report with child bands
- improved split mechanism (added Tfrx
Str
etcheable.HasNextDataPart for complicated data like RTF tables)
- improved crosstab speed when using repeat band with crosstab
object
version 4.9
---------------
+ added outline to PDF export
+ added anchors to PDF export
- fixed bug with embedded TTC fonts in PDF export
+ added an ability to create multiimage TIFF files
+ added export headers/foo
ter
s in ODF export
+ added ability to print/export transparent pictures (properties TfrxPictureView.Transparent and TfrxPictureView.TransparentColor) (PDF export isn't supported)
+ added new "split to sheet" modes for TfrxXMLExport
+ added support of /PAGE tag in TfrxRichView, engine automatically break report pages when find /PAGE tag
+ added ability to hide Null values in TfrxChartView (TfrxChartView.IgnoreNulls = True)
+ added ability to set any custom page order for printing (i.e. 3,2,1,5,4 )
+ [en
ter
prise] added variables "AUTHLOGIN" and "AUTHGROUP" inside the any report
+ [en
ter
prise] now any report file can be matched with any (one and more) group, these reports are accessible only in matched groups
+ [en
ter
prise] now you can set-up cache delays for each report file (reports.xml)
+ [en
ter
prise] added new properties editor for reports in Configuration utility (see Reports tab)
+ [en
ter
prise] added property "Xml" - "Split
Type
" in server configuration - allow to select split on pages
type
between none/pages/printonprev/rowscount
+ [en
ter
prise] added property "Xml" - "SplitRowsCount" in server configuration - sets the count of rows for "rowscount" split
type
+ [en
ter
prise] added property "Xml" - "Extension" in server configuration - allow select between ".xml" and ".xls" extension for output file
+ [en
ter
prise] added property "Html" - "URLTarget" in server configuration - allow select the target
attribute
for report URLs
+ [en
ter
prise] added property "ReportsFile" - path to file with reports to groups associations and cache delays
+ [en
ter
prise] added property "ReportsLi
stR
enewTimeout" in server configuration
+ [en
ter
prise] added property "ConfigRenewTimeout" in server configuration
+ [en
ter
prise] added property "Mime
Type
" for each output format in server configuration
+ [en
ter
prise] added property "BrowserPrint" in server configuration - allow printing by browser, added new template nav_print_browser.html
+ [en
ter
prise] added dynamic file name generation of resulting formats (report_name_date_time)
* [en
ter
prise] SERVER_REPORTS_LIST and SERVER_REPORTS_HTML variables (list of available reports) depend from user group (for in
ter
nal authentification)
+ added drawing shapes in PDF export (not bitmap)
+ added rotated text in PDF export (not bitmap)
+ added EngineOptions.IgnoreDevByZero property allow to ignore division by zero exception in expressions
+ added properties TfrxDBLookupComboBox.DropDownWidth, TfrxDBLookupComboBox.DropDownRows
+ added event TfrxCustomExportFil
ter
.OnBeginExport
+ added ability to decrease font size in barcode
object
+ added ability to inseret FNC1 to "code 128" barcode
+ added event TfrxPreview.OnMouseDown
+ added support of new unicode-PDF export in D4-D6 and BCB4-BCB6
* improved AddFrom method - anchor coping
- fixed bug with WordWrap in PDF export
- fixed bug with underlines in PDF export
- fixed bug with rounded rectangles in PDF export
- fixed CSV export to fit to the RFC 4180 specification
- fixed bug with
str
ikeout text in PDF export
- fixed bug with incorrect export of TfrxRichView
object
in RTF format (wrong line spacing)
- [en
ter
prise] added critical section in TfrxServerLog.Write
- fixed bug with setting up of the Protection Flags in the PDF export dialog window
- fixed bug in PDF export (file
str
ucture)
- fixed bug with pictures in Open Office Wri
ter
(odt) export
- [en
ter
prise] fixed bug with TfrxReportServer component in Delphi 2010
- fixed minor errors in Embarcedero RAD Studio 2010
- fixed bug with endless loop with using vertical bands together with page header and header with ReprintOnNewPage
- fixed bug when using "Keeping" and Cross tables (incorrect cross transfer)
- fixed bug with [CopyName#] macros when use "Join small pages" print mode
- fixed bug when try to split page with endless height to several pages (NewPage, StartNewPage)
- fixed bug with empty line TfrxRichView when adding text via expression
- fixed bug when Foo
ter
prints even if main band is invisible (Foo
ter
Af
ter
Each = True)
- fixed resetting of Page variable in double-pass report with TfrxCrossView
- fixed bug with loosing of aligning when split TfrxRichView
- fixed buzz in reports with TfrxRichView when using RTF 4.1
version 4.8
---------------
+ added support of Embarcadero Rad Studio 2010 (Delphi/C++Builder)
+ added TfrxDBDataset.BCDToCurrency property
+ added TfrxReportOptions.HiddenPassword property to set password silently from code
+ added TfrxADOConnection.OnAf
ter
Disconnect event
+ added TfrxDesigner.MemoParentFont property
+ added new TfrxDesignerRe
str
iction: drDontEditReportScript and drDontEditIn
ter
nalDatasets
+ adedd checksum calculating for 2 5 in
ter
leaved barcode
+ added TfrxGroupHeader.ShowChildIfDrillDown property
+ added TfrxMailExport.OnSendMail event
+ added RTF 4.1 support for TfrxRichText
object
+ [en
ter
prise] added Windows Authentification mode
+ added confirmation reading for TfrxMailExport
+ added TimeOut field to TfrxMailExport form
+ added ability to use keeping(KeepTogether/KeepChild/KeepHeader) in multi-column report
+ added ability to split big bands(biggest than page height) by default
* [en
ter
prise] improved CGI for IIS/Apache server
* changed PDF export (D7 and upper): added full unicode support, improved performance, decreased memory requirements
old PDF export engine saved in file frxExportPDF_old.pas
- changed inheritance mechanism, correct inherits of linked
object
s (fixups)
- fixed bug with Mirror Mrgins in RTF, HTML, XLS, XML, OpenOffice exports
- fixed bug when cross tab cut the text in corner, when corner height grea
ter
than column height
- [fs] improved script compilation
- improved WatchForm TListBox changet to TCheckListBox
- improved AddFrom method - copy outline
- Improved functional of vertical bands, shows memos placed on H-band which doesn't across VBand, also calculate expression inside it and call events (like in FR2)
- Improved unsorted mode in crosstab(join same columns correctly)
- Improved conver
ter
from Report Builder
- Improved TfrxDesigner.OnInsert
Object
, should call when drag&drop field from data
tree
- improved DrillDownd mechanism, should work correct with mas
ter
-detail-subtetail nesting
- fixed bug with DownThenAcross in Cross Tab
- fixed several bugs under CodeGear RAD Studio (Delphi/C++Builder) 2009
- fixed bug with emf in ODT export
- fixed bug with outline when build several composite reports in double pass mode
- fixed bug when group doesn't fit on the whole page
- fixed "Page" and "Line" variables inside vertical bands
- fixed bug with using KeepHeader in some cases
- fixed bug with displacement of subreport when use PrintOnParent property in some cases
- fixed small memory leak in subreports
- fixed problem with PageFoo
ter
and ReportSymmary when use PrintOnPreviousPage property
- fixed bug when designer shows commented functions in
object
inspector
- fixed bug when designer place function in commented text block
- fixed bug when Engine try to split non-
str
etcheable view and gone to endless loop
- fixed bug with HTML tags in memo when use shot text and WordWrap
- [en
ter
prise] fixed bug with variables lost on refresh/export
- fixed bug whih PDF,ODT export in Delphi4 and CBuilder4
- fixed bug with some codepage which use two bytes for special symbols (Japanese ans Chinese codepages)
- fixed bug when engine delete first space from text in split Memo
- fixed bug in multi-column page when band overlap
str
etched PageHeader
- fixed bug with using ReprintOnNewPage
version 4.7
---------------
+ CodeGear RAD Studio (Delphi/C++Builder) 2009 support
+ [en
ter
prise] enchanced error description in logs
+ added properties TfrxHTMLExport.HTMLDocumentBegin: T
Str
ings,
TfrxHTMLExport.HTMLDocumentBody: T
Str
ings, TfrxHTMLExport.HTMLDocumentEnd: T
Str
ings
+ improved RTF export (with line spacing, vertical gap etc)
+ added support of Enhanced Metafile (EMF) images in Rich Text (RTF), Open Office (ODS), Excel (XLS) exports
+ added OnAf
ter
ScriptCompile event
+ added onLoadRecentFile Event
+ added C++ Builder demos
+ added hot-key Ctrl + mouseWheel - Change scale in designer
+ added TfrxMemoView.AnsiText property
- fixed bug in RTF export with EMF pictures in OpenOffice Wri
ter
- fixed some multi-thread isuues in engine, PDF, ODF exports
- [en
ter
prise] fixed integrated template of report navigator
- [en
ter
prise] fixed bug with export in In
ter
net Explorer browser
- fixed bug with font size of dot-matix reports in Excel and XML exports
- fixed bug in e-mail export with many addresses
- fixed bug in XLS export (with fast export unchecked and image
object
is null)
- [en
ter
prise] fixed bug in TfrxReportServer.OnGetVariables event
- fixed bug in Calcl function
- fixed memory leak in Cross editor
- fixed progress bar and find dialog bug in DualView
- fixed bug in PostNET and ean13 barcodes
- fixed bug with TruncOutboundText in Dot Matrix report
- fixed bugs with break points in syntaxis memo
- improved BeforeConnect event in ADO
- fixed bug in inhehited report with in
ter
nal dataset
- fixed bug in TfrxPanelControl with background color(Delphi 2005 and above)
version 4.6
---------------
+ added & , < , > to XML reader
+ added <nowrap> tag, the text concluded in tag is not broken by WordWrap, it move entirely
+ added ability to move band without
object
s (Alt + Move)
+ added ability to output pages in the preview from right to left ("many pages" mode), for RTL languages(PreviewOptions.RTLPreview)
+ added ability to storing picture cache in "temp" file (PreviewOptions.PictureCacheInFile)
+ added EngineOptions.UseGlobalDataSetList (added for multi-thread applications) - set it to False if you don't want use Global DataSet list(use Report.EnabledDataSet.Add() to add dataset in local list)
+ added new property Hint for all printed
object
s, hints at the dialog
object
s now shows in StatusBar
+ added new property TfrxDBLookupComboBox.AutoOpenDataSet (automatically opens the attached dataset af
ter
onActivate event)
+ added new property TfrxReportPage.PageCount like TfrxDataBand.RowCount
+ added new property WordWrap for dialog buttons (Delphi 7 and above).
+ added sort by name to data
tree
+ added TfrxDesigner.TemplatesExt property
+ added TfrxStyles class in script rtti
+ changes in the Chart editor: ability to change the name of the series, ability to move created series, other small changes
+ [en
ter
prise] added configurations values refresh in run-time
+ [en
ter
prise] added new demo \Demos\ClientServer\ISAPI
+ [en
ter
prise] added output to server prin
ter
s from user browser (see config.xml "AllowPrint", set to "no" by default), note: experimental feature
+ [en
ter
prise] added reports list refresh in run-time
+ [en
ter
prise] added templates feature
+ [en
ter
prise] improved speed and stability
+ [fs] added TfsScript.IncludePath property
+ [fs] added TfsScript.UseClassLateBinding property
+ [fs] fixed
type
casting from variant(
str
ing) to integer/float
- changes in report inherit: FR get relative path from current loaded report(old reports based on application path works too)
- corrected module for converting reports from Report Builder
- fixed bug in CrossTab when set charset different from DEFAULT_CHARSET
- fixed bug in RTF export with some TfrxRichView
object
s
- fixed bug when print on landscape orientation with custom paper size
- fixed bug when use network path for parent report
- fixed bug with Band.Allowslit = True and ColumnFoo
ter
- fixed bug with drawing subreport on
str
etched band
- fixed bug with embedded fonts in PDF export
- fixed bug with long ReportTitle + Header + Ma
ter
Data.KeepHeader = true
- fixed bug with minimizing of Modal designer in BDS2005 and above
- fixed bug with paths in HTML export
- fixed bug with RTL in PDF export
- fixed bug with SubReport in multi column page
- fixed bug with Subreport.PrintOnParent = true in inherited report
- fixed bug with SYMBOL_CHARSET in PDF export
- fixed bug with the addition of datasets by inheritance report
- fixed bug with width calculation when use HTML tags in memo
- fixed compatibility with Wide
Str
ings module in BDS2006/2007
- fixed flicking in preview when use OnClick
Object
event
- fixed free space calculation when use PrintOnPreviousPage
- fixed preview bug with winXP themes and in last update
- fixed subreports inherit
- Thumbnail and Outline shows at right side for RTL languages
- [fs] fixed bug with late binding
version 4.5
---------------
+ added Conver
ter
RB2FR.pas unit for converting reports from Report Builder to Fast Report
+ added Conver
ter
QR2FR.pas unit for converting reports from QuickReport to Fa
stR
eport
+ added support of multiple attachments in e-mail export (html with images as example)
+ added support of unicode (UTF-8) in e-mail export
+ added ability to change templates path in designer
+ added OnReportPrint script event
+ added PNG support in all version (start from Basic)
+ added TfrxDMPMemoView.TruncOutboundText property - truncate outbound text in matrix report when WordWrap=false
+ added new frames styles fsAltDot and fsSquare
+ added new event OnPreviewDblClick in all TfrxView components
+ added ability to call dialogs event af
ter
report run when set De
str
oyForms = false
+ added ability to change AllowExpressions and HideZeros properties in cross Cells (default=false)
+ added IgnoreDupParams property to DB components
+ added auto open dataset in TfrxDBLookupComboBox
+ added new property TfrxADOQuery.Lock
Type
+ added define DB_CAT (frx.inc) for grouping DB components
+ added TfrxPictureView.HightQuality property(draw picture in preview with hight quality, but slow down drawing procedure)
+ [FRViewer] added comandline options "/print filename" and "/silent_print filename"
+ added unicode input support in RichEditor
+ added new define HOOK_WNDPROC_FOR_UNICODE (frx.inc) - set hook on GetMessage function for unicode input support in D4-D7/BCB4-BCB6
+ added ability chose path to FIB packages in "Recompile Wizard"
+ added new function TfrxPreview.GetTopPosition, return a position on current preview page
+ added new hot-keys to Code Editor - Ctrl+Del delete the word before cursor, Ctrl+BackSpace delete the word af
ter
cursor(as in Delhi IDE)
+ added "MDI Designer" example
- all language resources moved to UTF8, XML
- fixed bug with html tags [sup] and [sub]
- fixed width calculation in TfrxMemoView when use HTML tags
- fixed bug with suppressRepeated in Vertical bands
- fixed bug when designer not restore scrollbars position af
ter
undo/redo
- fixed visual bug in toolbars when use Windows Vista + XPManifest + Delphi 2006
- fixed bug in CalcHeight when use negative LineSpace
- fixed bug in frx2xto30 when import query/table components, added import for TfrDBLookupControl component
- fixed bug with Cross and TfrxHeader.ReprintOnNewPage = true
- fixed converting from unicode in TfrxMemoView when use non default charset
- [fs] fixed bug with "in" operator
- fixed bug with aggregate function SUM
- fixed bug when use unicode
str
ing with [TotalPages#] in TfrxMemoView
- fixed bug with TSQLTimeStampField field
type
- fixed designer dock-panels("
Object
Inspector", "Report
Tree
", "Data
Tree
") when use designer as MDI or use several non-modal designer windows
- fixed bug with hide/show dock-panels("
Object
Inspector", "Report
Tree
", "Data
Tree
"), now it restore size af
ter
hiding
- fixed bug in XML/XLS export - wrong encode numbers in memo af
ter
CR/LF
- fiexd bug in RTF export
- fixed bug with undo/redo commands in previewPages designer
- fixed bug with SuppressRepeated when use KeepTogether in group
- fixed bug with SuppressRepeated on new page all events fired twice(use Engine.SecondScriptcall to de
ter
minate it)
version 4.4
---------------
+ added support for CodeGear RAD Studio 2007
+ improved speed of PDF, HTML, RTF, XML, ODS, ODT exports
+ added TfrxReportPage.BackPictureVisible, BackPicturePrintable properties
+ added rtti for the TfrxCrossView.CellFunctions property
+ added properties TfrxPDFExport.Keywords, TfrxPDFExport.Producer, TfrxPDFExport.HideToolbar,
TfrxPDFExport.HideMenubar, TfrxPDFExport.HideWindowUI, TfrxPDFExport.FitWindow,
TfrxPDFExport.Cen
ter
Window, TfrxPDFExport.PrintScaling
+ added ability recompile frxFIB packages in "recompile wizard"
+ added ability to set color property for all teechart series which support it
+ added, setting frame style for each frame line in style editor
+ added TfrxPreview.Locked property and TfrxPreview.DblClick event
+ added 'invalid password' exception when load report without crypt
+ added new parame
ter
to InheritFromTemplate (by default = imDefault) imDefault - show Error dialog, imDelete - delete duplicates, imRename - rename duplicates
+ added property TfrxRTFExport.AutoSize (default is "False") for set vertical autosize in table cells
* redesigned dialog window of PDF export
* improved WYSIWYG in PDF export
- fixed bug, the PageFoo
ter
band overlap the ReportSummary band when use EndlessHeight
- fixed bug with lage paper height in preview
- fixed bug with outline and encryption in PDF export
- fixed bug with solid arrows in PDF export
- fixed bug when print TfrxHeader on a new page if ReprintOnNewPage = true and KeepFoo
ter
= True
- fixed bug when used AllowSplit and TfrxGroupHeader.KeepTogether
- fixed page numbers when print dotMatrix report without dialog
- fixed bug with EndlessHeight in multi-columns report
- fixed font dialog in rich editor
- [fs] fixed bug when create TWide
Str
ings in script code
- fixed bug with dialog form when set TfrxButtonControl.Default property to True
- fixed twice duplicate name error in PreviewPages designer when copy - past
object
- fixed bug with Preview.Clear and ZmWholePage mode
- fixed bug with using "outline" together "embedded fonts" options in PDF export
- fixed multi-thread bug in PDF export
- fixed bug with solid fill of transparent rectangle shape in PDF export
- fixed bug with export OEM_CODEPAGE in RTF, Excel exports
- fixed bug with vertical size of single page in RTF export
- fixed bug with vertical arrows in PDF export
- fixed memory leak with inherited reports
version 4.3
---------------
+ added support for C++Builder 2007
+ added encryption in PDF export
+ added TeeChart Pro 8 support
+ added support of OEM code page in PDF export
+ added TfrxReport.CaseSensitiveExpressions property
+ added "OverwritePrompt" property in all export components
+ improved RTF export (WYSIWYG)
+ added support of thai and vietnamese charsets in PDF export
+ added support of arrows in PDF export
* at inheritance of the report the script from the report of an ancestor is added to the current report (as comments)
* some changes in PDF export core
- fixed bug with number formats in Open Document Spreadsheet export
- fixed bug when input text in number property(
Object
Inspector) and close Designer(without apply changes)
- fixed bug in TfrxDBDataset with reCurrent
- fixed bug with memory leak in export of empty outline in PDF format
- line# fix (bug with subreports)
- fixed bug with edit prepared report with rich
object
- fixed bug with shadows in PDF export
- fixed bug with arrows in designer
- fixed bug with margins in HTML, RTF, XLS, XML exports
- fixed bug with arrows in exports
- fixed bug with prin
ter
s enumeration in designer (list index of bound)
- fixed papersize bug in inherited reports
version 4.2
---------------
+ added support for CodeGear Delphi 2007
+ added export of html tags in RTF format
+ improved split of the rich
object
+ improved split of the memo
object
+ added TfrxReportPage.ResetPageNumbers property
+ added support of underlines property in PDF export
* export of the memos formatted as fkNumeric to float in ODS export
- fixed bug keeptogether with aggregates
- fixed bug with double-line draw in RTF export
- fix multi-thread problem in PDF export
- fixed bug with the shading of the paragraph in RTF export when ex
ter
nal rich-text was inserted
- fixed bug with unicode in xml/xls export
- fixed bug in the crop of page in BMP, TIFF, Jpeg, Gif
- "scale" printmode fixed
- group & userdataset bugfix
- fixed cross-tab pagination error
- fixed bug with round brackets in PDF export
- fixed bug with gray to black colors in RTF export
- fixed outline with page.endlessheight
- fixed SuppressRepeated & new page
- fixed bug with long time export in text format
- fixed bug with page range and outline in PDF export
- fixed undo in code window
- fixed error when call DesignReport twice
- fixed unicode in the cross
object
- fixed designreportinpanel with dialog forms
- fixed paste of DMPCommand
object
- fixed bug with the export of null images
- fixed code completion bug
- fixed column foo
ter
& report summary problem
version 4.1
---------------
+ added ability to show designer inside panel (TfrxReport.DesignReportInPanel method). See new demo Demos\EmbedDesigner
+ added TeeChart7 Std support
+ [server] added "User" parame
ter
in TfrxReportServer.OnGetReport, TfrxReportServer.OnGetVariables and TfrxReportServer.OnAf
ter
BuildReport events
+ added Cross.KeepTogether property
+ added TfrxReport.PreviewOptions.PagesInCache property
- barcode fix (export w/o preview bug)
- fixed bug in preview (AV with zoommode = zmWholePage)
- fixed bug with outline + drilldown
- fixed datasets in inherited report
- [install] fixed bug with library path set up in BDS/Turbo C++ Builder installation
- fixed pagefoo
ter
position if page.EndlessWidth is true
- fixed shift bug
- fixed design-time inheritance (folder issues)
- fixed chm help file path
- fixed embedded fonts in PDF
- fixed preview buttons
- fixed bug with syntax highlight
- fixed bug with print scale mode
- fixed bug with control.Hint
- fixed edit preview page
- fixed memory leak in cross-tab
version 4.0 initial release
---------------------
Report Designer:
- new XP-style in
ter
face
- the "Data" tab with all report datasets
- ability to draw diagrams in the "Data" tab
- code completion (Ctrl+Space)
- breakpoints
- watches
- report templates
- local guidelines (appears when you move or resize an
object
)
- ability to work in non-modal mode, mdi child mode
Report Preview:
- thumbnails
Print:
- split a big page to several small pages
- print several small pages on one big
- print a page on a specified sheet (with scale)
- duplex handling from print dialogue
- print copy name on each printed copy (for example, "First copy", "Second copy")
Report Core:
- "endless page" mode
- images handling, increased speed
- the "Reset page numbers" mode for groups
- reports crypting (Rijndael algorithm)
- report inheritance (both file-based and dfm-based)
- drill-down groups
- frxGlobalVariables
object
- "cross-tab"
object
enhancements:
- improved cells appearance
- cross elements visible in the designer
- fill corner (ShowCorner property)
- side-by-side crosstabs (NextCross property)
- join cells with the same value (JoinEqualCells property)
- join the same
str
ing values in a cell (AllowDuplicates property)
- ability to put an ex
ter
nal
object
inside cross-tab
- AddWidth, AddHeight properties to increase width&height of the cell
- AutoSize property, ability to resize cells manually
- line
object
can have arrows
- added TfrxPictureView.FileLink property (can contain variable or a file name)
- separate settings for each frame line (properties Frame.LeftLine,
TopLine, RightLine, BottomLine can be set in the
object
inspector)
- PNG images support (uncomment {$DEFINE PNG} in the frx.inc file)
- Open Document Format for Office Applications (OASIS) exports, spreadsheet (ods) and text (odt)
En
ter
prise components:
- Users/Groups security support (see a demo application Demos\ClientServer\UserManager)
- Templates support
- Dynamically refresh of configuration, users/groups
D2010以上版本(D14_D19)安装必读
delphi2010以上版本(D14_D19)使用者安装时,请将res\frccD14_D19.exe更名名为frcc.exe
frccD14_D19.exe是专门的delphi2010以上版本(D14_D19)编码器。其他低delphi版本,请使用frcc.exe
keras-gpu = 2.3.1
今天在以TensorFlow2.1.0为后端的Keras中使用TensorBoard时
报错
,发现原因是keras和tf.keras混用导致的。
报错
与
解决方案
如下:
导致
报错
语句:
summary = TensorBoard(log_dir="cnn_lstm_logs/",histogram_freq=1)
---> 54 summary = TensorBoard(log_dir="cnn_lstm_log
Table of Contents
Header Files The #define Guard Header File Dependencies Inline Functions The -inl.h Files Function Parame
ter
Ordering Names and Order of Includes
Scoping Namespaces Nested Classes Nonmember, Static Member, and Global Functions Local Variables Static and Global Variables
Classes Doing Work in Con
str
uctors Default Con
str
uctors Explicit Con
str
uctors Copy Con
str
uctors
Str
ucts vs. Classes Inheritance Multiple Inheritance In
ter
faces Operator Overloading Access Control Declaration Order Write Short Functions
Google-Specific Magic Smart Poin
ter
s cpplint
Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time
Type
Information (RTTI) Casting
Str
eams Preincrement and Predecrement Use of const Integer
Type
s 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x
Naming General Naming Rules File Names
Type
Names Variable Names Constant Names Function Names Namespace Names Enumerator Names Macro Names Exceptions to Naming Rules
Comments Comment Style File Comments Class Comments Function Comments Variable Comments Implementation Comments Punctuation, Spelling and Grammar TODO Comments Deprecation Comments
Formatting Line Length Non-ASCII Charac
ter
s Spaces vs. Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Poin
ter
and Reference Expressions Boolean Expressions Return Values Variable and Array Initialization Preprocessor Directives Class Format Con
str
uctor Initializer Lists Namespace Formatting Horizontal Whitespace Vertical Whitespace
Exceptions to the Rules Existing Non-conformant Code Windows Code
Important Note
Displaying Hidden Details in this Guide
link ▶This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below.
Hooray! Now you know you can expand points to get more details. Al
ter
natively, there's an "expand all" at the top of this document.
Background
C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain.
The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively.
Style, also known as readability, is what we call the conventions that govern our C++ code. The
ter
m Style is a bit of a misnomer, since these conventions cover far more than just source file formatting.
One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pat
ter
n-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and pat
ter
ns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency.
Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we con
str
ain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is re
str
icted.
Open-source projects developed by Google conform to the requirements in this guide.
Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.
Header Files
In general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function.
Correct use of header files can make a huge difference to the readability, size and performance of your code.
The following rules will guide you through the various pitfalls of using header files.
The #define Guard
link ▶All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be ___H_.
To guarantee uniqueness, they should be based on the full path in a project's source
tree
. For example, the file foo/src/bar/baz.h in project foo should have the following guard:
#ifndef FOO_BAR_BAZ_H_
#define FOO_BAR_BAZ_H_
#endif // FOO_BAR_BAZ_H_
Header File Dependencies
link ▶Don't use an #include when a forward declaration would suffice.
When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files.
You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include "file/base/file.h".
How can we use a class Foo in a header file without access to its definition?
We can declare data members of
type
Foo* or Foo&.
We can declare (but not define) functions with arguments, and/or return values, of
type
Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument con
str
uctor, in which case we need the full definition to support automatic
type
conversion.)
We can declare static data members of
type
Foo. This is because static data members are defined outside the class definition.
On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of
type
Foo.
Sometimes it makes sense to have poin
ter
(or bet
ter
, scoped_ptr) members instead of
object
members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files.
Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files.
Note: If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h, instead of myfile.cc.
Inline Functions
link ▶Define functions inline only when they are small, say, 10 lines or less.
Definition:
You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism.
Pros:
Inlining a function can generate more efficient
object
code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions.
Cons:
Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs fas
ter
due to bet
ter
use of the in
str
uction cache.
Decision:
A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of de
str
uctors, which are often longer than they appear because of implicit member- and base-de
str
uctor calls!
Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed).
It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators.
The -inl.h Files
link ▶You may use file names with a -inl.h suffix to define complex inline functions when needed.
The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in .cc files, and we do not like to have much actual code in .h files unless there is a readability or performance advantage.
If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implemen
ter
and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary.
Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read.
Do not forget that a -inl.h file requires a #define guard just like any other header file.
Function Parame
ter
Ordering
link ▶When defining a function, parame
ter
order is: inputs, then outputs.
Parame
ter
s to C/C++ functions are either input to the function, output from the function, or both. Input parame
ter
s are usually values or const references, while output and input/output parame
ter
s will be non-const poin
ter
s. When ordering function parame
ter
s, put all input-only parame
ter
s before any output parame
ter
s. In particular, do not add new parame
ter
s to the end of the function just because they are new; place new input-only parame
ter
s before the output parame
ter
s.
This is not a hard-and-fast rule. Parame
ter
s that are both input and output (often classes/
str
ucts) muddy the wa
ter
s, and, as always, consistency with related functions may require you to bend the rule.
Names and Order of Includes
link ▶Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h.
All of a project's header files should be listed as descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included as
#include "base/logging.h"
In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:
dir2/foo2.h (preferred location — see details below).
C system files.
C++ system files.
Other libraries' .h files.
Your project's .h files.
The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first .h file #included in some .cc.
dir/foo.cc and dir2/foo2.h are often in the same directory (e.g. base/basic
type
s_test.cc and base/basic
type
s.h), but can be in different directories too.
Within each section it is nice to order the includes alphabetically.
For example, the includes in google-awesome-project/src/foo/in
ter
nal/fooserver.cc might look like this:
#include "foo/public/fooserver.h" // Preferred location.
#include
#include
#include
#include
#include "base/basic
type
s.h"
#include "base/commandlineflags.h"
#include "foo/public/bar.h"
Scoping
Namespaces
link ▶Unnamed namespaces in .cc files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive.
Definition:
Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope.
Pros:
Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.
For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, project1::Foo and project2::Foo are now distinct symbols that do not collide.
Cons:
Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.
Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR).
Decision:
Use namespaces according to the policy described below.
Unnamed Namespaces
Unnamed namespaces are allowed and even encouraged in .cc files, to avoid runtime naming conflicts:
namespace { // This is in a .cc file.
// The content of a namespace is not indented
enum { kUnused, kEOF, kError }; // Commonly used tokens.
bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF.
} // namespace
However, file-scope declarations that are associated with a particular class may be declared in that class as
type
s, static data members or static member functions rather than as members of an unnamed namespace.
Ter
minate the unnamed namespace as shown, with a comment // namespace.
Do not use unnamed namespaces in .h files.
Named Namespaces
Named namespaces should be used as follows:
Namespaces wrap the entire source file af
ter
includes, gflags definitions/declarations, and forward declarations of classes from other namespaces:
// In the .h file
namespace mynamespace {
// All declarations are within the namespace scope.
// Notice the lack of indentation.
class MyClass {
public:
void Foo();
} // namespace mynamespace
// In the .cc file
namespace mynamespace {
// Definition of functions is within scope of the namespace.
void MyClass::Foo() {
} // namespace mynamespace
The typical .cc file might have more complex detail, including the need to reference classes in other namespaces.
#include "a.h"
DEFINE_bool(someflag, false, "dummy flag");
class C; // Forward declaration of class C in the global namespace.
namespace a { class A; } // Forward declaration of a::A.
namespace b {
...code for b... // Code goes against the left margin.
} // namespace b
Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file.
You may not use a using-directive to make all names from a namespace available.
// Forbidden -- This pollutes the namespace.
using namespace foo;
You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files.
// OK in .cc files.
// Must be in a function, method or class in .h files.
using ::foo::bar;
Namespace aliases are allowed anywhere in a .cc file, anywhere inside the named namespace that wraps an entire .h file, and in functions and methods.
// Shorten access to some commonly used names in .cc files.
namespace fbz = ::foo::bar::baz;
// Shorten access to some commonly used names (in a .h file).
namespace librarian {
// The following alias is available to all files including
// this header (in namespace librarian):
// alias names should therefore be chosen consistently
// within a project.
namespace pd_s = ::pipeline_diagnostics::sidetable;
inline void my_inline_function() {
// namespace alias local to a function (or method).
namespace fbz = ::foo::bar::baz;
} // namespace librarian
Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible.
Nested Classes
link ▶Although you may use public nested classes when they are part of an in
ter
face, consider a namespace to keep declarations out of the global scope.
Definition:
A class can define another class within it; this is also called a member class.
class Foo {
private:
// Bar is a member class, nested within Foo.
class Bar {
Pros:
This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the ou
ter
scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation.
Cons:
Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* poin
ter
will have to include the full class declaration for Foo.
Decision:
Do not make nested classes public unless they are actually part of the in
ter
face, e.g., a class that holds a set of options for some method.
Nonmember, Static Member, and Global Functions
link ▶Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely.
Pros:
Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace.
Cons:
Nonmember and static member functions may make more sense as members of a new class, especially if they access ex
ter
nal resources or have significant dependencies.
Decision:
Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on ex
ter
nal variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead.
Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library.
If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope.
Local Variables
link ▶Place a function's variables in the narrowest scope possible, and initialize variables in the declaration.
C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what
type
the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g.
int i;
i = f(); // Bad -- initialization separate from declaration.
int j = g(); // Good -- declaration has initialization.
Note that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g.
while (const char* p =
str
chr(
str
, '/'))
str
= p + 1;
There is one caveat: if the variable is an
object
, its con
str
uctor is invoked every time it en
ter
s scope and is created, and its de
str
uctor is invoked every time it goes out of scope.
// Inefficient implementation:
for (int i = 0; i < 1000000; ++i) {
Foo f; // My ctor and dtor get called 1000000 times each.
f.DoSomething(i);
It may be more efficient to declare such a variable used in a loop outside that loop:
Foo f; // My ctor and dtor get called once each.
for (int i = 0; i < 1000000; ++i) {
f.DoSomething(i);
Static and Global Variables
link ▶Static or global variables of class
type
are forbidden: they cause hard-to-find bugs due to inde
ter
minate order of con
str
uction and de
str
uction.
Object
s with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or poin
ter
s, or arrays/
str
ucts of POD.
The order in which class con
str
uctors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class
type
, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals.
Likewise, the order in which de
str
uctors are called is defined to be the reverse of the order in which the con
str
uctors were called. Since con
str
uctor order is inde
ter
minate, so is de
str
uctor order. For example, at program-end time a static variable might have been de
str
oyed, but code still running -- perhaps in another thread -- tries to access it and fails. Or the de
str
uctor for a static '
str
ing' variable might be run prior to the de
str
uctor for another variable that contains a reference to that
str
ing.
As a result we only allow static variables to contain POD data. This rule completely disallows vector (use C arrays instead), or
str
ing (use const char []).
If you need a static or global variable of a class
type
, consider initializing a poin
ter
(which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw poin
ter
, not a "smart" poin
ter
, since the smart poin
ter
's de
str
uctor will have the order-of-de
str
uctor issue that we are trying to avoid.
Classes
Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class.
Doing Work in Con
str
uctors
link ▶In general, con
str
uctors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method.
Definition:
It is possible to perform initialization in the body of the con
str
uctor.
Pros:
Convenience in typing. No need to worry about whether the class has been initialized or not.
Cons:
The problems with doing work in con
str
uctors are:
There is no easy way for con
str
uctors to signal errors, short of using exceptions (which are forbidden).
If the work fails, we now have an
object
whose initialization code failed, so it may be an inde
ter
minate state.
If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion.
If someone creates a global variable of this
type
(which is against the rules, but still), the con
str
uctor code will be called before main(), possibly breaking some implicit assumptions in the con
str
uctor code. For instance, gflags will not yet have been initialized.
Decision:
If your
object
requires non-trivial initialization, consider having an explicit Init() method. In particular, con
str
uctors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc.
Default Con
str
uctors
link ▶You must define a default con
str
uctor if your class defines member variables and has no other con
str
uctors. Otherwise the compiler will do it for you, badly.
Definition:
The default con
str
uctor is called when we new a class
object
with no arguments. It is always called when calling new[] (for arrays).
Pros:
Initializing
str
uctures by default, to hold "impossible" values, makes debugging much easier.
Cons:
Extra work for you, the code wri
ter
.
Decision:
If your class defines member variables and has no other con
str
uctors you must define a default con
str
uctor (one that takes no arguments). It should preferably initialize the
object
in such a way that its in
ter
nal state is consistent and valid.
The reason for this is that if you have no other con
str
uctors and do not define a default con
str
uctor, the compiler will generate one for you. This compiler generated con
str
uctor may not initialize your
object
sensibly.
If your class inherits from an existing class but you add no new member variables, you are not required to have a default con
str
uctor.
Explicit Con
str
uctors
link ▶Use the C++ keyword explicit for con
str
uctors with one argument.
Definition:
Normally, if a con
str
uctor takes one argument, it can be used as a conversion. For instance, if you define Foo::Foo(
str
ing name) and then pass a
str
ing to a function that expects a Foo, the con
str
uctor will be called to convert the
str
ing into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new
object
s created without you meaning them to. Declaring a con
str
uctor explicit prevents it from being invoked implicitly as a conversion.
Pros:
Avoids undesirable conversions.
Cons:
None.
Decision:
We require all single argument con
str
uctors to be explicit. Always put explicit in front of one-argument con
str
uctors in the class definition: explicit Foo(
str
ing name);
The exception is copy con
str
uctors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments.
Copy Con
str
uctors
link ▶Provide a copy con
str
uctor and assignment operator only when necessary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN.
Definition:
The copy con
str
uctor and assignment operator are used to create copies of
object
s. The copy con
str
uctor is implicitly invoked by the compiler in some situations, e.g. passing
object
s by value.
Pros:
Copy con
str
uctors make it easy to copy
object
s. STL containers require that all contents be copyable and assignable. Copy con
str
uctors can be more efficient than CopyFrom()-style workarounds because they combine con
str
uction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation.
Cons:
Implicit copying of
object
s in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which
object
s are being passed around by value as opposed to by reference, and therefore where changes to an
object
are reflected.
Decision:
Few classes need to be copyable. Most should have neither a copy con
str
uctor nor an assignment operator. In many situations, a poin
ter
or reference will work just as well as a copied value, with bet
ter
performance. For example, you can pass function parame
ter
s by reference or poin
ter
instead of by value, and you can store poin
ter
s rather than
object
s in an STL container.
If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy con
str
uctor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy con
str
uctor and assignment operator.
If your class does not need a copy con
str
uctor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy con
str
uctor and assignment operator in the private: section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error).
For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used:
// A macro to disallow the copy con
str
uctor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(
Type
Name) \
Type
Name(const
Type
Name&); \
void operator=(const
Type
Name&)
Then, in class Foo:
class Foo {
public:
Foo(int f);
~Foo();
private:
DISALLOW_COPY_AND_ASSIGN(Foo);
Str
ucts vs. Classes
link ▶Use a
str
uct only for passive
object
s that carry data; everything else is a class.
The
str
uct and class keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-
type
you're defining.
str
ucts should be used for passive
object
s that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., con
str
uctor, de
str
uctor, Initialize(), Reset(), Validate().
If more functionality is required, a class is more appropriate. If in doubt, make it a class.
For consistency with STL, you can use
str
uct instead of class for functors and traits.
Note that member variables in
str
ucts and classes have different naming rules.
Inheritance
link ▶Composition is often more appropriate than inheritance. When using inheritance, make it public.
Definition:
When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and in
ter
face inheritance, in which only method names are inherited.
Pros:
Implementation inheritance reduces code size by re-using the base class code as it specializes an existing
type
. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. In
ter
face inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API.
Cons:
For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class.
Decision:
All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead.
Do not overuse implementation inheritance. Composition is often more appropriate. Try to re
str
ict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of" Foo.
Make your de
str
uctor virtual if necessary. If your class has virtual methods, its de
str
uctor should be virtual.
Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private.
When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to de
ter
mine if the function is virtual or not.
Multiple Inheritance
link ▶Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure in
ter
face classes tagged with the In
ter
face suffix.
Definition:
Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are pure in
ter
faces and those that have an implementation.
Pros:
Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance).
Cons:
Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution.
Decision:
Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure in
ter
faces. In order to ensure that they remain pure in
ter
faces, they must end with the In
ter
face suffix.
Note: There is an exception to this rule on Windows.
In
ter
faces
link ▶Classes that satisfy certain conditions are allowed, but not required, to end with an In
ter
face suffix.
Definition:
A class is a pure in
ter
face if it meets the following requirements:
It has only public pure virtual ("= 0") methods and static methods (but see below for de
str
uctor).
It may not have non-static data members.
It need not have any con
str
uctors defined. If a con
str
uctor is provided, it must take no arguments and it must be protected.
If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the In
ter
face suffix.
An in
ter
face class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the in
ter
face can be de
str
oyed correctly, they must also declare a virtual de
str
uctor (in an exception to the first rule, this should not be pure). See
Str
ou
str
up, The C++ Programming Language, 3rd edition, section 12.4 for details.
Pros:
Tagging a class with the In
ter
face suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the case of multiple inheritance. Additionally, the in
ter
face concept is already well-understood by Java programmers.
Cons:
The In
ter
face suffix lengthens the class name, which can make it harder to read and understand. Also, the in
ter
face property may be considered an implementation detail that shouldn't be exposed to clients.
Decision:
A class may end with In
ter
face only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with In
ter
face.
Operator Overloading
link ▶Do not overload operators except in rare, special circumstances.
Definition:
A class can define that operators such as + and / operate on the class as if it were a built-in
type
.
Pros:
Can make code appear more intuitive because a class will behave in the same way as built-in
type
s (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators.
Cons:
While operator overloading can make code more intuitive, it has several drawbacks:
It can fool our intuition into thinking that expensive operations are cheap, built-in operations.
It is much harder to find the call sites for overloaded operators. Searching for Equals() is much easier than searching for relevant invocations of ==.
Some operators work on poin
ter
s too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug.
Overloading also has surprising ramifications. For instance, if a class overloads unary operator&, it cannot safely be forward-declared.
Decision:
In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared.
However, there may be rare cases where you need to overload an operator to in
ter
operate with templates or "standard" C++ classes (such as operator<<(o
str
eam&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor
type
s when declaring the container.
Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why.
See also Copy Con
str
uctors and Function Overloading.
Access Control
link ▶Make data members private, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected when using Google Test). Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private.
The definitions of accessors are usually inlined in the header file.
See also Inheritance and Function Names.
Declaration Order
link ▶Use the specified order of declarations within a class: public: before private:, methods before data members (variables), etc.
Your class definition should start with its public: section, followed by its protected: section and then its private: section. If any of these sections are empty, omit them.
Within each section, the declarations generally should be in the following order:
Type
defs and Enums
Constants (static const data members)
Con
str
uctors
De
str
uctor
Methods, including static methods
Data Members (except static const data members)
Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the class. See Copy Con
str
uctors.
Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible.
Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details.
Write Short Functions
link ▶Prefer small and focused functions.
We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the
str
ucture of the program.
Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code.
You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces.
Google-Specific Magic
There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere.
Smart Poin
ter
s
link ▶If you actually need poin
ter
semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when
object
s need to be held by STL containers. You should never use auto_ptr.
"Smart" poin
ter
s are
object
s that act like poin
ter
s but have added semantics. When a scoped_ptr is de
str
oyed, for instance, it deletes the
object
it's pointing to. shared_ptr is the same way, but implements reference-counting so only the last poin
ter
to an
object
deletes it.
Generally speaking, we prefer that we design code with clear
object
ownership. The clearest
object
ownership is obtained by using an
object
directly as a field or local variable, without using poin
ter
s at all. On the other extreme, by their very definition, reference counted poin
ter
s are owned by nobody. The problem with this design is that it is easy to create circular references or other
str
ange conditions that cause an
object
to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned.
Although they are not recommended, reference counted poin
ter
s are sometimes the simplest and most elegant way to solve a problem.
cpplint
link ▶Use cpplint.py to detect style errors.
cpplint.py is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting // NOLINT at the end of the line.
Some projects have in
str
uctions on how to run cpplint.py from their project tools. If the project you are contributing to does not, you can download cpplint.py separately.
Other C++ Features
Reference Arguments
link ▶All parame
ter
s passed by reference must be labeled const.
Definition:
In C, if a function needs to modify a variable, the parame
ter
must use a poin
ter
, eg int foo(int *pval). In C++, the function can al
ter
natively declare a reference parame
ter
: int foo(int &val).
Pros:
Defining a parame
ter
as reference avoids ugly code like (*pval)++. Necessary for some applications like copy con
str
uctors. Makes it clear, unlike with poin
ter
s, that NULL is not a possible value.
Cons:
References can be confusing, as they have value syntax but poin
ter
semantics.
Decision:
Within function parame
ter
lists all references must be const:
void Foo(const
str
ing &in,
str
ing *out);
In fact it is a very
str
ong convention in Google code that input arguments are values or const references while output arguments are poin
ter
s. Input parame
ter
s may be const poin
ter
s, but we never allow non-const reference parame
ter
s.
One case when you might want an input parame
ter
to be a const poin
ter
is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the
object
; it is usually best to document this in comments as well. STL adap
ter
s such as bind2nd and mem_fun do not permit reference parame
ter
s, so you must declare functions with poin
ter
parame
ter
s in these cases, too.
Function Overloading
link ▶Use overloaded functions (including con
str
uctors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called.
Definition:
You may write a function that takes a const
str
ing& and overload it with another that takes const char*.
class MyClass {
public:
void Analyze(const
str
ing &text);
void Analyze(const char *text, size_t textlen);
Pros:
Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors.
Cons:
If a function is overloaded by the argument
type
s alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function.
Decision:
If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., Append
Str
ing(), AppendInt() rather than just Append().
Default Arguments
link ▶We do not allow default function parame
ter
s, except in a few uncommon situations explained below.
Pros:
Often you have a function that uses lots of default values, but occasionally you want to override the defaults. Default parame
ter
s allow an easy way to do this without having to define many functions for the rare exceptions.
Cons:
People often figure out how to use an API by looking at existing code that uses it. Default parame
ter
s are more difficult to maintain because copy-and-paste from previous code may not reveal all the parame
ter
s. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code.
Decision:
Except as described below, we require all arguments to be explicitly specified, to force programmers to consider the API and the values they are passing for each argument rather than silently accepting defaults they may not be aware of.
One specific exception is when default arguments are used to simulate variable-length argument lists.
// Support up to 4 params by using a default empty AlphaNum.
str
ing
Str
Cat(const AlphaNum &a,
const AlphaNum &b = gEmptyAlphaNum,
const AlphaNum &c = gEmptyAlphaNum,
const AlphaNum &d = gEmptyAlphaNum);
Variable-Length Arrays and alloca()
link ▶We do not allow variable-length arrays or alloca().
Pros:
Variable-length arrays have natural-looking syntax. Both variable-length arrays and alloca() are very efficient.
Cons:
Variable-length arrays and alloca are not part of Standard C++. More importantly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: "It ran fine on my machine, but dies mys
ter
iously in production".
Decision:
Use a safe allocator instead, such as scoped_ptr/scoped_array.
Friends
link ▶We allow use of friend classes and functions, within reason.
Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a FooBuilder class be a friend of Foo so that it can con
str
uct the inner state of Foo correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests.
Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is bet
ter
than making a member public when you want to give only one other class access to it. However, most classes should in
ter
act with other classes solely through their public members.
Exceptions
link ▶We do not use C++ exceptions.
Pros:
Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes.
Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with
Python
, Java, and the C++ that others are familiar with.
Some third-party C++ libraries use exceptions, and turning them off in
ter
nally makes it harder to integrate with those libraries.
Exceptions are the only way for a con
str
uctor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively.
Exceptions are really handy in testing frameworks.
Cons:
When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program
ter
minating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly.
More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This causes maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand.
Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it.
Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure.
The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these re
str
ictions!
Decision:
On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.
Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat grea
ter
than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available al
ter
natives to exceptions, such as error codes and assertions, introduce a significant burden.
Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch.
There is an exception to this rule (no pun intended) for Windows code.
Run-Time
Type
Information (RTTI)
link ▶We do not use Run Time
Type
Information (RTTI).
Definition:
RTTI allows a programmer to query the C++ class of an
object
at run time.
Pros:
It is useful in some unittests. For example, it is useful in tests of factory classes where the test has to verify that a newly created
object
has the expected dynamic
type
.
In rare circumstances, it is useful even outside of tests.
Cons:
A query of
type
during run-time typically means a design problem. If you need to know the
type
of an
object
at runtime, that is often an indication that you should reconsider the design of your class.
Decision:
Do not use RTTI, except in unittests. If you find yourself in need of writing code that behaves differently based on the class of an
object
, consider one of the al
ter
natives to querying the
type
.
Virtual methods are the preferred way of executing different code paths depending on a specific subclass
type
. This puts the work within the
object
itself.
If the work belongs outside the
object
and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pat
ter
n. This allows a facility outside the
object
itself to de
ter
mine the
type
of class using the built-in
type
system.
If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with
type
tags.
Casting
link ▶Use C++ casts like static_cast(). Do not use other cast formats like int y = (int)x; or int y = int(x);.
Definition:
C++ introduced a different cast system from C that distinguishes the
type
s of cast operations.
Pros:
The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g., (int)3.5) and sometimes you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them.
Cons:
The syntax is nasty.
Decision:
Do not use C-style casts. Instead, use these C++-style casts.
Use static_cast as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a poin
ter
from a class to its superclass.
Use const_cast to remove the const qualifier (see const).
Use rein
ter
pret_cast to do unsafe conversions of poin
ter
type
s to and from integer and other poin
ter
type
s. Use this only if you know what you are doing and you understand the aliasing issues.
Do not use dynamic_cast except in test code. If you need to know
type
information at runtime in this way outside of a unittest, you probably have a design flaw.
Str
eams
link ▶Use
str
eams only for logging.
Definition:
Str
eams are a replacement for printf() and scanf().
Pros:
With
str
eams, you do not need to know the
type
of the
object
you are printing. You do not have problems with format
str
ings not matching the argument list. (Though with gcc, you do not have that problem with printf either.)
Str
eams have automatic con
str
uctors and de
str
uctors that open and close the relevant files.
Cons:
Str
eams make it difficult to do functionality like pread(). Some formatting (particularly the common format
str
ing idiom %.*s) is difficult if not impossible to do efficiently using
str
eams without using printf-like hacks.
Str
eams do not support operator reordering (the %1s directive), which is helpful for in
ter
nationalization.
Decision:
Do not use
str
eams, except where required by a logging in
ter
face. Use printf-like routines instead.
There are various pros and cons to using
str
eams, but in this case, as in many other cases, consistency trumps the debate. Do not use
str
eams in your code.
Extended Discussion
There has been debate on this issue, so this explains the reasoning in grea
ter
depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain
type
of I/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using
str
eams or using printf plus Read/Write/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons.
Proponents of
str
eams have argued that
str
eams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of
str
eams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the
type
of the
object
to be printing. This is a fair point. But, there is a downside: you can easily use the wrong
type
, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using
str
eams.
cout << this; // Prints the address
cout << *this; // Prints the contents
The compiler does not generate an error because << has been overloaded. We discourage overloading for just this reason.
Some say printf formatting is ugly and hard to read, but
str
eams are often no bet
ter
. Consider the following two fragments, both with the same typo. Which is easier to discover?
cerr << "Error connecting to '" <bar()->hostname.first
<< ":" <bar()->hostname.second << ": " <bar()->hostname.first, foo->bar()->hostname.second,
str
error(errno));
And so on and so forth for any issue you might bring up. (You could argue, "Things would be bet
ter
with the right wrappers," but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.)
Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on printf + read/write.
Preincrement and Predecrement
link ▶Use prefix form (++i) of the increment and decrement operators with i
ter
ators and other template
object
s.
Definition:
When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement).
Pros:
When the return value is ignored, the "pre" form (++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy of i to be made, which is the value of the expression. If i is an i
ter
ator or other non-scalar
type
, copying i could be expensive. Since the two
type
s of increment behave the same when the value is ignored, why not just always pre-increment?
Cons:
The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (i) precedes the "verb" (++), just like in English.
Decision:
For simple scalar (non-
object
) values there is no reason to prefer one form and we allow either. For i
ter
ators and other template
type
s, use pre-increment.
Use of const
link ▶We
str
ongly recommend that you use const whenever it makes sense to do so.
Definition:
Declared variables and parame
ter
s can be preceded by the keyword const to indicate the variables are not changed (e.g., const int foo). Class functions can have the const qualifier to indicate the function does not change the state of the class member variables (e.g., class Foo { int Bar(char c) const; };).
Pros:
Easier for people to understand how variables are being used. Allows the compiler to do bet
ter
type
checking, and, conceivably, generate bet
ter
code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs.
Cons:
const is viral: if you pass a const variable to a function, that function must have const in its proto
type
(or the variable will need a const_cast). This can be a particular problem when calling library functions.
Decision:
const variables, data members, methods and arguments add a level of compile-time
type
checking; it is bet
ter
to detect errors as soon as possible. Therefore we
str
ongly recommend that you use const whenever it makes sense to do so:
If a function does not modify an argument passed by reference or by poin
ter
, that argument should be const.
Declare methods to be const whenever possible. Accessors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const poin
ter
or non-const reference to a data member.
Consider making data members const whenever they do not need to be modified af
ter
con
str
uction.
However, do not go crazy with const. Something like const int * const * const x; is likely overkill, even if it accurately describes how const x is. Focus on what's really useful to know: in this case, const int** x is probably sufficient.
The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first.
Where to put the const
Some people favor the form int const *foo to const int* foo. They argue that this is more readable because it's more consistent: it keeps the rule that const always follows the
object
it's describing. However, this consistency argument doesn't apply in this case, because the "don't go crazy" dictum eliminates most of the uses you'd have to be consistent with. Putting the const first is arguably more readable, since it follows English in putting the "adjective" (const) before the "noun" (int).
That said, while we encourage putting const first, we do not require it. But be consistent with the code around you!
Integer
Type
s
link ▶Of the built-in C++ integer
type
s, the only one used is int. If a program needs a variable of a different size, use a precise-width integer
type
from , such as int16_t.
Definition:
C++ does not specify the sizes of its integer
type
s. Typically people assume that short is 16 bits, int is 32 bits, long is 32 bits and long long is 64 bits.
Pros:
Uniformity of declaration.
Cons:
The sizes of integral
type
s in C++ can vary based on compiler and architecture.
Decision:
defines
type
s like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. Of the C integer
type
s, only int should be used. When appropriate, you are welcome to use standard
type
s like size_t and ptrdiff_t.
We use int very often, for integers we know are not going to be too big, e.g., loop coun
ter
s. Use plain old int for such things. You should assume that an int is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer
type
, use int64_t or uint64_t.
For integers we know can be "big", use int64_t.
You should not use the unsigned integer
type
s such as uint32_t, unless the quantity you are representing is really a bit pat
ter
n rather than a number, or unless you need defined twos-complement overflow. In particular, do not use unsigned
type
s to say a number will never be negative. Instead, use assertions for this.
On Unsigned Integers
Some people, including some textbook authors, recommend using unsigned
type
s to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider:
for (unsigned int i = foo.Length()-1; i >= 0; --i) ...
This code will never
ter
minate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's
type
-promotion scheme causes unsigned
type
s to behave differently than one might expect.
So, document that a variable is non-negative using assertions. Don't use an unsigned
type
.
64-bit Portability
link ▶Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and
str
ucture alignment.
printf() specifiers for some
type
s are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file int
type
s.h):
// printf macros for size_t, in the style of int
type
s.h
#ifdef _LP64
#define __PRIS_PREFIX "z"
#else
#define __PRIS_PREFIX
#endif
// Use these macros af
ter
a % in a printf format
str
ing
// to get correct 32/64 bit behavior, like this:
// size_t size = records.size();
// printf("%"PRIuS"\n", size);
#define PRIdS __PRIS_PREFIX "d"
#define PRIxS __PRIS_PREFIX "x"
#define PRIuS __PRIS_PREFIX "u"
#define PRIXS __PRIS_PREFIX "X"
#define PRIoS __PRIS_PREFIX "o"
Type
DO NOT use DO use Notes
void * (or any poin
ter
) %lx %p
int64_t %qd, %lld %"PRId64"
uint64_t %qu, %llu, %llx %"PRIu64", %"PRIx64"
size_t %u %"PRIuS", %"PRIxS" C99 specifies %zu
ptrdiff_t %d %"PRIdS" C99 specifies %zd
Note that the PRI* macros expand to independent
str
ings which are concatenated by the compiler. Hence if you are using a non-constant format
str
ing, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., af
ter
the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x).
Remember that sizeof(void *) != sizeof(int). Use intptr_t if you want a poin
ter
-sized integer.
You may need to be careful with
str
ucture alignments, particularly for
str
uctures being stored on disk. Any class/
str
ucture with a int64_t/uint64_t member will by default end up being 8-byte aligned on a 64-bit system. If you have such
str
uctures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to al
ter
str
ucture alignment. For gcc, you can use __
attribute
__((packed)). MSVC offers #pragma pack() and __declspec(align()).
Use the LL or ULL suffixes a