Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c++ - Creating an instance of class

What's the difference between lines 1 , 2 , 3 , 4?

When do I use each?

Why line 3 prints the constructor Foo and line 7 returns an error and line 8 doesn't?

#include <iostream>     
using namespace std;

class Foo
 {
   public:
   Foo ( )
   {
      cout << "constructor Foo
";
   }               
};

class Bar
 {
   public:
   Bar ( Foo )
   {
      cout << "constructor Bar
";
   }
};

int main()
{
   /* 1 */ Foo* foo1 = new Foo ();
   /* 2 */ Foo* foo2 = new Foo;
   /* 3 */ Foo foo3;
   /* 4 */ Foo foo4 = Foo::Foo();

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );
   /* 6 */ Bar* bar2 = new Bar ( *new Foo );
   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

   return 1;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
   /* 1 */ Foo* foo1 = new Foo ();

Creates an object of type Foo in dynamic memory. foo1 points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo was a POD-type, this would perform value-initialization (it doesn't apply here).

   /* 2 */ Foo* foo2 = new Foo;

Identical to before, because Foo is not a POD type.

   /* 3 */ Foo foo3;

Creates a Foo object called foo3 in automatic storage.

   /* 4 */ Foo foo4 = Foo::Foo();

Uses copy-initialization to create a Foo object called foo4 in automatic storage.

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );

Uses Bar's conversion constructor to create an object of type Bar in dynamic storage. bar1 is a pointer to it.

   /* 6 */ Bar* bar2 = new Bar ( *new Foo );

Same as before.

   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );

This is just invalid syntax. You can't declare a variable there.

   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

Would work and work by the same principle to 5 and 6 if bar3 wasn't declared on in 7.

5 & 6 contain memory leaks.

Syntax like new Bar ( Foo::Foo() ); is not usual. It's usually new Bar ( (Foo()) ); - extra parenthesis account for most-vexing parse. (corrected)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...