在C++ 11中,新的通用初始化语法也可用于调用普通构造函数(不接受initializer_list参数).虽然看起来不错,但我认为这可能会导致实际使用中出现问题.
因此,假设在我的项目中,我使用了以下类附带的库:
class Foo
{
public:
Foo(int size, int value); // create 'size' number of elements
Foo(initializer_list<int> list); // create elements as in 'list'
}
Run Code Online (Sandbox Code Playgroud)
在项目中,它以这种方式使用:
Foo foo{10, 2}; // initialize foo with 2 elements: 10 and 2
Run Code Online (Sandbox Code Playgroud)
现在该库得到了一个新版本,在新版本中,作者删除了第二个构造函数,该构造函数接受了initializer_list(无论是出于目的还是出错).我没有注意到变化,我的项目像以前一样快乐地构建,只是意外的foo被初始化(现在它是10个元素而不是2个).
这个问题的另一个版本是Foo只有第一个构造函数,你使用通用初始化语法来初始化foo,现在作者已经决定添加第二个构造函数,这同样会导致foo被初始化为不同的元素而不会被注意到.
只想知道其他人对此的看法.这是一个真正的问题还是我担心太多?是否有任何解决方案可以防止这种情况发生?谢谢.
我正在使用gcc 4.6.1使用可变参数模板参数.以下代码按预期编译:
template<typename RetType, typename... ArgTypes>
class Event;
template<typename RetType, typename... ArgTypes>
class Event<RetType(ArgTypes...)>
{
public:
typedef function<RetType(ArgTypes...)> CallbackType;
void emit(ArgTypes...args)
{
for (CallbackType callback : callbacks)
{
callback(args...);
}
}
private:
vector<CallbackType> callbacks;
};
Run Code Online (Sandbox Code Playgroud)
但令我惊讶的是,下面只有一个"Argument Type"的"普通"版本无法编译:
template<typename RetType, typename ArgType>
class Event;
template<typename RetType, typename ArgType>
class Event<RetType(ArgType)> // <- error: wrong number of template arguments (1, should be 2)
{};
Run Code Online (Sandbox Code Playgroud)
g ++ 4.6.1在注释中给出了错误.
任何人都知道它为什么会导致错误以及如何使其工作?另外,我认为上面的代码是"模板部分专业化"的一种形式吗?
我正在玩这个例子来理解右值引用:
#include <string>
#include <iostream>
#include <utility>
#include <vector>
class Dog
{
public:
Dog() {};
Dog(Dog&& a) { std::cout << "R value" << std::endl;}
};
Dog foo()
{
return Dog();
}
int main()
{
std::vector<Dog> v;
v.push_back(Dog()); // calls move constructor
Dog c((Dog())); // does not call move constructor
Dog d(foo()); // does not call move constructor
}
Run Code Online (Sandbox Code Playgroud)
我很难理解为什么在行v.push_back(Dog())中,对象Dog()被视为Rvalue(因此调用移动构造函数),但以下两行不会调用移动构造函数.我想我可能会误解匿名对象和RValue之间的关系.