3

我正在尝试编写自己的智能指针 (C++11) 和堆栈有一个问题,可以通过下一个示例来解释:

#include <iostream>

template<typename T_Type>
class TestTemplateClass {
private:
    T_Type _state;

public:
    TestTemplateClass() : _state() {
        std::cout << "Default constructor" << std::endl;
    }

    TestTemplateClass(int inState) : _state(inState) {
        std::cout << "State constructor" << std::endl;
    }

    template<typename T_OtherType>
    TestTemplateClass(const TestTemplateClass<T_OtherType> &inValue) {
        std::cout << "Template-copy constructor" << std::endl;
    }

    template<typename T_OtherType>
    void operator = (const TestTemplateClass<T_OtherType> &inValue) {
        std::cout << "Operator" << std::endl;
    }

    ~TestTemplateClass() {
        std::cout << "Destructor" << std::endl;
    }
};

TestTemplateClass<int> createFunction() {
    return TestTemplateClass<int>();
}

int main() {
    TestTemplateClass<int> theReference = createFunction();
    std::cout << "Finished" << std::endl;
    return 0;
}

输出:

Default constructor
Destructor
Destructor
Finished
Destructor

如您所见,这里有很多析构函数。在我看来,复制省略和模板构造函数之间的交互存在一些问题,但我不知道这种错误可能是什么原因。我试图通过添加explicit复制构造函数和强制编译器使用我的模板构造函数来解决问题:

// After TestTemplateClass(int inState), but it's not important
explicit TestTemplateClass(const OwnType &inValue) {
    std::cout << "Copy constructor" << std::endl;
}

得到下一个输出:

Default constructor
Template-copy constructor
Destructor
Template-copy constructor
Destructor
Finished
Destructor

这里一切看起来都不错,但它看起来不像一个干净的解决方案。有更好的选择吗?

4

2 回答 2

5

(N)RVO永远不会在构造函数和析构函数调用的数量之间引入差异。它旨在使这基本上是不可能的。

问题出在您的代码上。根据语言规则,构造函数模板永远不会用于生成复制构造函数。复制构造函数永远不是模板,句号。

所以你的类模板实际上并没有声明一个复制构造函数,因此编译器会生成默认的(当然它不会打印任何东西)。如果您需要在复制构造函数中进行任何特殊处理,则必须始终手动声明它。模板永远不会用于实例化模板。

于 2015-03-12T08:00:01.357 回答
2

您的实验表明根本没有错误:第一个版本只是使用不打印任何内容的复制构造函数,而第二个版本使用不同的构造函数,因为您有效地禁用了它。

(看起来您使用的任何编译器和选项都不执行 RVO)

于 2015-03-12T07:53:01.130 回答