-1

What is the difference between the following three pieces of code with respect to MSVC?

Code 1: Foo ctor defined as:

Foo::Foo(Bar &bar = Bar());

Foo ctor used as:

Foo foo = new Foo();

Code 2: Foo ctor defined as:

Foo::Foo()
{
    Bar bar = Bar();
    Foo(bar);
}

Foo::Foo(Bar &bar);

Foo ctor used as:

Foo foo = new foo();

Code 3: Foo ctor defined as:

Foo::Foo(Bar &bar);

Foo ctor used as:

Bar bar = Bar();
Foo foo = new foo(bar);

Edit: Made corrections to the code. The intention was to explain the idea, didn't focus on the code, so made the mistake. Sorry about that.

The question specifically is to figure out the difference between code 2 and 3. Due to some reason, in the case of Code 2, the consumer of the Foo class ctor results in a crash and in case of Code 3 it doesn't. I don't have the specific code of the consumer, so cannot figure it out myself.

4

1 回答 1

3

在前两个中,您甚至没有调用构造函数,而是声明了一个函数:

Foo foo(); // function foo, returns a Foo object

要默认构造 a Foo,您需要

Foo foo;   // C++11 and C++03
Foo foo{}; // C++11

您的大部分代码要么是非法的,要么不符合您的预期。例如,这个构造函数除了创建一个局部Bar变量bar并尝试创建一个Foo同名的实例类型之外什么都不做:

Foo::Foo()
{
    Bar bar = Bar(); // local variable bar
    Foo(bar);        // error: 'bar' has a previous declaration as 'Bar bar'
}
于 2014-03-09T08:24:38.210 回答