模板化构造函数失去右值

时间:2014-10-31 10:53:50

标签: c++ templates

我在我的一个类中使用模板化构造函数

有人可以告诉我为什么这段代码没有警告或错误编译,但是一行代码(用默认的foo rvalue创建测试)就消失了!

#include <iostream>

class Foo
{
    int _value;
public:
    Foo()
    :_value(0)
    {
        std::cout << __PRETTY_FUNCTION__ << "value[" << _value << "]" << std::endl;
    }
    Foo(int value)
    :_value(value)
    {
        std::cout << __PRETTY_FUNCTION__ << "value[" << _value << "]" << std::endl;
    }
    Foo(Foo&& foo) = delete;
    Foo(const Foo& foo) = delete;
    friend std::ostream& operator << (std::ostream& output, const Foo& foo)
    {
        output << foo._value;
        return output;
    }
};
class Test
{
public:
    template <typename Type>
    Test(Type&& value)
    {
        std::cout << __PRETTY_FUNCTION__ << " with value[" << value << "]" << std::endl;
    }
    template <typename Type>
    void fn(Type&& value)
    {
        std::cout << __PRETTY_FUNCTION__ << " with value[" << value << "]" << std::endl;
    }
};

int main()
{
    std::cout << "//----- test fn with foo rvalue ---------------" << std::endl;
    Test test3(3);
    test3.fn(Foo());
    std::cout << "//----- test with int rvalue ------------------" << std::endl;
    Test test4(1+3);
    std::cout << "//----- create test with default foo rvalue ---" << std::endl;
    Test test5(Foo());
    std::cout << "//----- create test with foo rvalue -----------" << std::endl;
    Test test7 (Foo(1+6));
    std::cout << "//----- create test with moved foo rvalue -----" << std::endl;
    Test test8(std::move(Foo()));

    return 0;
}

这会产生以下结果

//----- test fn with foo rvalue ---------------
Test::Test(Type&&) [with Type = int] with value[3]
Foo::Foo()value[0]
void Test::fn(Type&&) [with Type = Foo] with value[0]
//----- test with int rvalue ------------------
Test::Test(Type&&) [with Type = int] with value[4]
//----- create test with default foo rvalue ---
//----- create test with foo rvalue -----------
Foo::Foo(int)value[7]
Test::Test(Type&&) [with Type = Foo] with value[7]
//----- create test with moved foo rvalue -----
Foo::Foo()value[0]
Test::Test(Type&&) [with Type = Foo] with value[0]

我正在使用g ++(Ubuntu 4.8.2-19ubuntu1)4.8.2 with std = c ++ 1y

如果有帮助,我在最后添加了一行

    std::cout << test5;

编译器发出警告

    warning: the address of ‘Test test5(Foo (*)())’ will always evaluate as ‘true’ [-Waddress]

1 个答案:

答案 0 :(得分:3)

Test test5(Foo());

它的功能声明,而不是对象创建。对于create对象,您可以使用以下

之一
Test test5((Foo()));
Test test5 = Test(Foo());
Test test5{Foo()};