请考虑以下代码:
class StringTokenizer
{
private:
char m_delimiter;
std::istringstream m_string;
public:
explicit StringTokenizer(const std::string& str, char delimiter)
: m_string(str)
, m_delimiter(delimiter)
{
}
template <class Container>
operator Container ()
{
Container container;
for (std::string token; std::getline(m_string, token, m_delimiter); )
{
container.insert(container.end(), token);
}
return container;
}
};
Run Code Online (Sandbox Code Playgroud)
这是用法:
vector<string> tmp = StringTokenizer("123 456", ' '); //Please note the implicit conversion
Run Code Online (Sandbox Code Playgroud)
调试时发生以下情况(使用VS2013):
在return转换运算符声明中
container由移动构造的新向量container 被破坏了功能返回后:
tmp 由复制构造函数构造我的问题是为什么不是tmp由移动构造函数构造的?
据我所知,函数返回类型是rvalue,应该移动.
我遇到了新的C++ 14签名std::max功能:
template< class T >
const T& max( const T& a, const T& b ); // (C++11)
template< class T >
constexpr const T& max( const T& a, const T& b );// (C++14)
Run Code Online (Sandbox Code Playgroud)
我已经阅读了关于C++ 14的轻松constexpr限制提议,但我仍然不明白为什么这个函数的返回值可以是constexpr
例:
std::vector<int> a, b;
//This does not compile but as my understadnding of `constexpr` this should
int array[std::max(a.size(), b.size()]; (1)
//This is trivial use that does compile
int array[std::max(1,2)]; (2)
Run Code Online (Sandbox Code Playgroud)
当忽略std::max(1)中的呼叫时constexpr?
请考虑以下代码:
Class* p = nullptr; //global var
Run Code Online (Sandbox Code Playgroud)
此代码由线程1执行:
p = new Class;
Run Code Online (Sandbox Code Playgroud)
此代码在线程2上执行:
if (p != nullptr) ...; // does the standard gurantee that the pointer will be assigned only after object is constructed ?
Run Code Online (Sandbox Code Playgroud)
我的问题是标准强制执行何时p分配指向分配的内存?例1:
p 被指定指向新分配的内存Class调用'sc`tor并将分配的内存传递给它例2:
Class调用'sc`tor并将分配的内存传递给它p 被指定指向新分配的内存请考虑以下代码:
class Abc
{
public:
Abc() { std::cout << " ABC::ABC\n"; }
Abc& doIT() { std::cout << " Abc::doIT\n"; return *this; }
~Abc() { std::cout << " ABC::~ABC\n"; }
};
Run Code Online (Sandbox Code Playgroud)
用法:
const Abc& ap = Abc().doIT(); //After this line ap references garbage
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么临时Abc被摧毁而没有绑定到ap?