把一个std::unique_ptr内部std::tuple工作没有任何问题,但是当tuple包含另一个tuple具有共同unique_ptr的元素,则编译器会引发错误。
例子:
std::tuple<int, std::unique_ptr<Entity>> tupleA {1, std::move(new Entity)};
//this line throws an error!
std::tuple<std::tuple<int, int>, std::unique_ptr<Entity>> tupleB {{1, 1}, std::move(new Entity)};
Run Code Online (Sandbox Code Playgroud)
error: no matching constructor for initialization of ´std::tuple<std::tuple<int, int>,std::unique_ptr<Entity>>´
note: candidate constructor template not viable: cannot convert initializer list argument to ´std::allocator_arg_t´
Run Code Online (Sandbox Code Playgroud)
这里的问题究竟是什么?
我想编写一个小程序,该程序应snprintf()以以下方式使用该函数反转字符串的字符。那是我注意到一些奇怪的地方。
int main() {
char dest[5] = "";
char source[5] = "abc";
for (int i = 0; i < 4; i++) {
char c = source[i];
snprintf(dest, 5, "%c%s", c, dest); //here, the current character gets appended in front
//of the String "dest" using snprintf() "recursively"
}
}
Run Code Online (Sandbox Code Playgroud)
程序应该输出什么:cba
实际输出:ccba
在调试程序时,您可以看到最低的两个字节(dest[0]和dest[1])始终携带相同的信息。
有人知道为什么会发生这种情况以及如何防止这种情况发生吗?
如果我dest在参数中没有使用两次,而是使用了一个像这样的临时缓冲区:snprintf(temporary, 5, "%c%s", c, dest)然后snprintf(dest, 5, "%s", temporary)直接按预期工作。