13

给定这样的类:

class Foo {
public:
    Foo(int);

    Foo(const Foo&);

    Foo& operator=(int);

private:
    // ...
};

这两行是完全等价的,还是它们之间有细微的差别?

Foo f(42);

Foo f = 42;

编辑:我通过在原始问题中使 Foo 构造函数“显式”来混淆问题。我已将其删除,但感谢您的回答。

我还添加了复制构造函数的声明,以明确复制可能不是一个简单的操作。

我真正想知道的是,根据 C++ 标准,“Foo f = 42”会直接调用 Foo(int) 构造函数,还是会调用复制构造函数?

看起来 fasih.ahmed 有我正在寻找的答案(除非它是错误的)。

4

2 回答 2

20
class Foo {
public:
    Foo(explicit int);

    Foo& operator=(int);
};

That's invalid. The syntax is

class Foo {
public:
    explicit Foo(int);

    Foo& operator=(int);
};

The difference is that the conversion constructor cannot be used for implicit conversions when you put explicit before it:

Foo f(10); // works
Foo f = 10; // doesn't work

The above doesn't have anything to do with an assignment operator you declared there. It is not used since that is an initialization (only constructors are used). The following will use the assignment operator:

Foo f;
f = 10;

And will use the default constructor of Foo (the one taking no arguments).


Edit: The questioner changed his question to the specific ways of whether

Foo f = 1; // called "copy initialization" 
Foo f(1);  // called "direct initialization"

Are the same. The answer is that they are equivalent to the following:

Foo f(Foo(1));
Foo f(1);

If and only if the conversion constructor taking the int is not declared with keyword explicit, otherwise the first is a compiler error (see above). The compiler is allowed to elide (optimize out) the temporary passed to the copy constructor of Foo in the first case if all semantic restrictions are still safisfied, and even if the copy constructor has side effects. That especially includes a visible copy constructor.

于 2008-12-16T21:09:28.877 回答
9
Foo f = 42;

该语句将为值“42”创建一个临时对象。

Foo f(42);

该语句将直接分配值,因此减少了一次函数调用。

于 2008-12-16T20:53:07.303 回答