[C++] Object i = Object(0)和Object* i = new Object(0)的区别
C/C++里指针通常是指向一个对象的,所以不能指向某一变量(Object i,i为某个变量),不过在Java中所有变量都是对象
举个例子:
int a=1;
int *p=a;
报错:invalid conversion from 'int' to ' int* ';
int *a = new int(1);
int *p=a;
正常运行!
再来看一个较为复杂一点的例子(将一个二叉链表的结点类作为我们的Object):
template<class T>
struct BTNode
{
T data;
BTNode *left,*right;
BTNode(const T& item=T(),BTNode *lptr=NULL,BTNode *rptr=NULL):data(item),left(lptr),right(rptr){}
};
int main()
{
BTNode<char> a=BTNode<char>('D',NULL,NULL);
BTNode<char> *ap=a;
return 0;
}
同样地会报错:cannot convert 'BTNode<char>' to 'BTNode<char>*' int initialization
而这样做就可以了:
int main()
{
BTNode<char> *a=new BTNode<char>('D',NULL,NULL);
BTNode<char> *ap=a;
return 0;
}
以上问题的原因都是因为指针指向了某一变量而不是对象,而用new Object()则是生成的一个对象并将地址给=前面的指针
再来看StackOverFlow里的一个例子:
struct Foo { int value; // Foo stores an int, called value Foo(int v):value(v) {}; // Foo can be constructed (created) from an int explicit Foo(double d):value(d) {}; // Foo can be constructed (created) from a double // ^^^ note that keyword. It says that it can only be EXPLICITLY created from a double };
Foo i = Foo(0);
the above creates an int
literal, then constructs Foo i
with it using the Foo(int v)
constructor, then copy-constructs Foo i
from it. However, the standard allows the compiler to "elide" (skip) the copy constructor, and instead just construct Foo i
directly from the int
literal 0
.
Foo* i = new Foo(0);
this goes to the free store (typically implemented and called the heap), gets ahold of enough memory to store a Foo
, then constructs it with the integer literal 0. It then returns the address of this Foo
object, which is then used to initialize the pointer Foo* i
.