#define VS. const
#define BUFSIZE 20 const int bufsize = 20;
preprocess time compiler time
no type checking type checking
const变量没有放在内存中,放在符号表,编译时是文件内部链接,其他的文件不可见,一定要可见,需使用
extern,此时将分配空间
A const in C++ defaults to internal linkage; that is, it is visible only within the file
where it is defined and cannot be seen at link time by other translation units. You must
always assign a value to a const when you define it, except when you make an explicit
declaration using extern:
extern const int bufsize;
Normally, the C++ compiler avoids creating storage for a const, but instead holds the
definition in its symbol table. When you use extern with const, however, you force storage
to be allocated (this is also true for certain other cases, such as taking the address of
a const). Storage must be allocated because extern says “use external linkage,” which
means that several translation units must be able to refer to the item, which requires it
to have storage.
In the ordinary case, when extern is not part of the definition, no storage is allocated.
When the const is used, it is simply folded in at compile time.
const类型是否分配空间的情形:
Whether or not storage is reserved for a const in C++ depends on how it is used.
In general, if a const is used simply to replace a name with a value (just as you would
use a #define), then storage doesn’t have to be created for the const. If no storage is
created (this depends on the complexity of the data type and the sophistication of the
compiler), the values may be folded into the code for greater efficiency after type
checking, not before, as with #define. If, however, you take an address of a const (even
unknowingly, by passing it to a function that takes a reference argument) or you define it
as extern, then storage is created for the const.
(1)所指的内容不能改变,但是可以指向不同的地址
const int* u;
u is a pointer, which points to a const int.
no initialization is required because you’re
saying that u can point to anything (that is, it is not const), but the thing it points to
cannot be changed.
eg. int k = 20;
u = &k; //ok
*u = 30;//illegal
int i = 10;
u = &i; //ok
(2)指针的地址不能指向其他地址,但是所指的内容可以改变
int d=1; int* const u=&d;
u is a pointer, which is const, that points to an int.
Because the pointer itself is now the const, the compiler requires that it be given an
initial value that will be unchanged for the life of that pointer.
eg. *u = 20; //ok
int j = 10;
u = &j;//illegal
char* cp = "how"的问题
字符串"how"由编译器创建一个constant字符串数组,由首地址指引。而cp不是常指针,语法上
是不可以的,而是为了兼容C代码没有报错,这样也带来一个问题,任何修改这个字符串的行为
都将造成运行时错误,如cp[1] = 'i';//runtime error
解决的办法:
(1)不想cp指向的东西改变,使用const char* cp = "how";
(2)可能改变cp的内容,使用char cp[] = "how";
const type func(...)
For built-in types, it doesn’t matter whether you return by value as a const, so you
should avoid confusing the client programmer and leave off the const when returning a
built-in type by value.
Returning by value as a const becomes important when you’re dealing with user-defined
types. If a function returns a class object by value as a const, the return value of that
function cannot be an lvalue (that is, it cannot be assigned to or otherwise modified).
The reason const has no meaning when you’re returning a built-in type by value is that
the compiler already prevents it from being an lvalue (because it’s always a value, and
not a variable). Only when you’re returning objects of user-defined types by value does
it become an issue.
const in classes
Inside a class, const partially reverts to its meaning in C. It allocates storage within
each object and represents a value that is initialized once and then cannot change. The
use of const inside a class means “This is constant for the lifetime of the object.”
However, each different object may contain a different value for that constant.
eg.
class Fred {
const int size;//必须在初始化列表里初始化
public:
Fred(int sz);
void print();
};
Fred::Fred(int sz) : size(sz) {}
void Fred::print() { cout << size << endl; }
int main() {
Fred a(1), b(2), c(3);
a.print(), b.print(), c.print();
} ///:~
static const type in classes
The static keyword, in this situation, means “there’s only one instance, regardless of
how many objects of the class are created,” which is precisely what we need here: a member
of a class which is constant, and which cannot change from one object of the class to
another. Thus, a static const of a built-in type can be treated as a compile-time constant.
eg.
class
{
static const int size = 100;//initialize in the class
}
const objects & const member functions
eg.
#include <iostream>
using namespace std;
//: C08:ConstMember.cpp
class X {
int i;
public:
X(int ii);
int f() const;//const member func: can not modify member data
void set();
};
X::X(int ii) : i(ii) {}
int X::f() const //!!!NOTE!!!: this "const" can not be omitted!
{ return i; }
void X::set(){i = 10;}
int main() {
X x1(10);
const X x2(20);
x1.f();
x2.f();
x1.set();
//! x2.set();//illegal:const object can only call const member functions
} ///:~
#define BUFSIZE 20 const int bufsize = 20;
preprocess time compiler time
no type checking type checking
const变量没有放在内存中,放在符号表,编译时是文件内部链接,其他的文件不可见,一定要可见,需使用
extern,此时将分配空间
A const in C++ defaults to internal linkage; that is, it is visible only within the file
where it is defined and cannot be seen at link time by other translation units. You must
always assign a value to a const when you define it, except when you make an explicit
declaration using extern:
extern const int bufsize;
Normally, the C++ compiler avoids creating storage for a const, but instead holds the
definition in its symbol table. When you use extern with const, however, you force storage
to be allocated (this is also true for certain other cases, such as taking the address of
a const). Storage must be allocated because extern says “use external linkage,” which
means that several translation units must be able to refer to the item, which requires it
to have storage.
In the ordinary case, when extern is not part of the definition, no storage is allocated.
When the const is used, it is simply folded in at compile time.
const类型是否分配空间的情形:
Whether or not storage is reserved for a const in C++ depends on how it is used.
In general, if a const is used simply to replace a name with a value (just as you would
use a #define), then storage doesn’t have to be created for the const. If no storage is
created (this depends on the complexity of the data type and the sophistication of the
compiler), the values may be folded into the code for greater efficiency after type
checking, not before, as with #define. If, however, you take an address of a const (even
unknowingly, by passing it to a function that takes a reference argument) or you define it
as extern, then storage is created for the const.
(1)所指的内容不能改变,但是可以指向不同的地址
const int* u;
u is a pointer, which points to a const int.
no initialization is required because you’re
saying that u can point to anything (that is, it is not const), but the thing it points to
cannot be changed.
eg. int k = 20;
u = &k; //ok
*u = 30;//illegal
int i = 10;
u = &i; //ok
(2)指针的地址不能指向其他地址,但是所指的内容可以改变
int d=1; int* const u=&d;
u is a pointer, which is const, that points to an int.
Because the pointer itself is now the const, the compiler requires that it be given an
initial value that will be unchanged for the life of that pointer.
eg. *u = 20; //ok
int j = 10;
u = &j;//illegal
char* cp = "how"的问题
字符串"how"由编译器创建一个constant字符串数组,由首地址指引。而cp不是常指针,语法上
是不可以的,而是为了兼容C代码没有报错,这样也带来一个问题,任何修改这个字符串的行为
都将造成运行时错误,如cp[1] = 'i';//runtime error
解决的办法:
(1)不想cp指向的东西改变,使用const char* cp = "how";
(2)可能改变cp的内容,使用char cp[] = "how";
const type func(...)
For built-in types, it doesn’t matter whether you return by value as a const, so you
should avoid confusing the client programmer and leave off the const when returning a
built-in type by value.
Returning by value as a const becomes important when you’re dealing with user-defined
types. If a function returns a class object by value as a const, the return value of that
function cannot be an lvalue (that is, it cannot be assigned to or otherwise modified).
The reason const has no meaning when you’re returning a built-in type by value is that
the compiler already prevents it from being an lvalue (because it’s always a value, and
not a variable). Only when you’re returning objects of user-defined types by value does
it become an issue.
const in classes
Inside a class, const partially reverts to its meaning in C. It allocates storage within
each object and represents a value that is initialized once and then cannot change. The
use of const inside a class means “This is constant for the lifetime of the object.”
However, each different object may contain a different value for that constant.
eg.
class Fred {
const int size;//必须在初始化列表里初始化
public:
Fred(int sz);
void print();
};
Fred::Fred(int sz) : size(sz) {}
void Fred::print() { cout << size << endl; }
int main() {
Fred a(1), b(2), c(3);
a.print(), b.print(), c.print();
} ///:~
static const type in classes
The static keyword, in this situation, means “there’s only one instance, regardless of
how many objects of the class are created,” which is precisely what we need here: a member
of a class which is constant, and which cannot change from one object of the class to
another. Thus, a static const of a built-in type can be treated as a compile-time constant.
eg.
class
{
static const int size = 100;//initialize in the class
}
const objects & const member functions
eg.
#include <iostream>
using namespace std;
//: C08:ConstMember.cpp
class X {
int i;
public:
X(int ii);
int f() const;//const member func: can not modify member data
void set();
};
X::X(int ii) : i(ii) {}
int X::f() const //!!!NOTE!!!: this "const" can not be omitted!
{ return i; }
void X::set(){i = 10;}
int main() {
X x1(10);
const X x2(20);
x1.f();
x2.f();
x1.set();
//! x2.set();//illegal:const object can only call const member functions
} ///:~