为什么这个语句不会调用构造函数--C++

Ggi*_*cci 3 c++ templates most-vexing-parse

模板类和普通类:

template <typename Type>
class Holder
{
public:
    Holder(const Type& value) : held_(value)
    {
        cout << "Holder(const Type& value)" << endl;
    }
    Type& Ref() { return held_; }
private:
    Type held_;
};

class Animal
{
public:
    Animal(const Animal& rhs) { cout << "Animal(const Animal& rhs)" << endl; }
    Animal() { cout << "Animal()" << endl; }
    ~Animal() { cout << "~Animal" << endl; }
    void Print() const { cout << "Animal::Print()" << endl; }
};
Run Code Online (Sandbox Code Playgroud)

然后我想Holder<Animal>用这个语句实例化一个Holder<Animal> a(Animal());,但是,它失败了.我的意思Animal()是不被视为临时对象.而这句话并没有调用Holder构造函数.

如果有人可以解释?我不清楚.我猜a这里变成了一种类型.然后,我使用Holder<Animal> a = Holder<Animal>(Animal());,它运作良好.所以,这里有一些案例:

  1. Holder<Animal> a(Animal()); a.Ref().Print(); // error
  2. Holder<Animal> a = Holder<Animal>(Animal()); a.Ref().Print(); // ok
  3. Holder<int> b(4); b.Ref() = 10; cout << b.Ref() << endl; //ok

能说明吗?我只是对第一个声明感到困惑.以及此语句导致的错误信息:

GCC4.7.2: error: request for member 'Ref' in 'a', which is of non-class type 'Holder<Animal>(Animal (*)())'

VS10:error C2228: left of '.Ref' must have class/struct/union,error C2228: left of '.Print' must have class/struct/union

piw*_*iwi 7

该语句Holder<Animal> a(Animal());不创建变量,但声明一个函数返回a Holder<Animal>并在参数中获取一个函数.它通常被称为最令人烦恼的解析,因为这种歧义(人们会期望变量而不是函数声明).

Herb Sutter在这里解释了不同的可能语法.在C++ 11中,一种可能的解决方案是:

auto a = Holder<Animal> {};
Run Code Online (Sandbox Code Playgroud)

  • 或者如果您的C++编译器不是来自这个十年,请使用周围的parens:`Holder <Animal> a((Animal()));`*yuck*. (2认同)