选择要调用的构造函数
Picking a constructor to call
考虑以下代码
class MyClass
{
public:
MyClass( MyClass && );
template< typename ... T > MyClass( T&& ... );
};
如何区分这两个构造函数之间的调用?我可以专门化模板化的模板,只调用原始模板吗?
以下是示例用例(这正是我在实际代码中所做的(:
MyClass c( MyClass { } );
在C++17 中启动
MyClass c( MyClass { } );
总是要呼叫
template< typename ... T > MyClass( T&& ... );
原因是不再有临时对象了。相反,初始化被省略,c
直接从"临时"的初始化器构造而来。这意味着你现在真正拥有的是
MyClass c{};
不过,这是一件好事,因为我们现在只是构建,而不是构建和移动,这是性能上的胜利。
这是Nathans答案的附录,因为您还没有接受它。
#include <iostream>
class MyClass
{
public:
MyClass() {
std::cout << "defaultn";
}
MyClass(MyClass&& rhs) {
std::cout<< "movingn";
}
template<typename ... T >
MyClass(T&& ... ts) {
std::cout << "ctor templaten";
}
};
int main()
{
MyClass a(MyClass{}); // only default ctor, no move
std::cout << "---n";
MyClass b(MyClass{"bork"}); // only template ctor, no move
std::cout << "---n";
MyClass c = std::move(a); // plain move
}
演示
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 减少复制构造函数调用
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 在 Google 测试中,我可以从构造函数调用 GetParam() 吗?
- C++ - 从另一个类构造函数调用类构造函数
- 在C++中初始化带有和不使用构造函数调用的对象有什么区别
- 是否可以从移动构造函数调用默认构造函数?
- 在模板生成器模式中分解重复的构造函数调用
- std::atexit 从全局对象的构造函数调用时的排序
- 对构造函数调用的约束
- 编译器错过了无效的构造函数调用,并调用不存在的(或私有的)默认构造函数
- 用构造函数调用填充向量
- 创建指针时是否没有构造函数调用
- 使用 emplace_back 避免移动构造函数调用的最佳方法?
- C++ 抽象类构造函数调用
- 为什么函数参数将带有参数的构造函数调用
- 为什么比“构造函数”调用更多的“解构器”调用
- 将对象传递给函数并不是导致构造函数调用