【发布时间】:2018-08-06 12:16:08
【问题描述】:
std::string 损坏的示例导致范围及其值结束:
#include <bits/stdc++.h>
const int StackSize = 2137;
char stack[StackSize];
template <typename Type>
Type& push(Type value) {
char *ptr = (char*)&value;
std::copy_n(ptr, sizeof(Type), stack);
return *(Type*)stack;
}
template <typename Type>
Type& create(Type value) {
auto &var = push<Type>(value);
std::cout << "Should Be: " << var << '\n';
return var;
}
int main() {
auto &x = create<std::string>("Hello");
std::cout << "Is: " << x << '\n';
}
当我更改函数 push 以接收指针时,输出是正确的,但目前它是“b”
我知道 std::string 有一个指向 c-string 的指针,并且输出不同,因为函数 push 的参数在作用域结束时被破坏。
但是为什么当我传递一个指针来推送时,输出仍然是正确的? c-string 应该在 create 结束后销毁。
【问题讨论】:
-
请显示替代代码而不是描述它。
-
push... 中有太多未定义的行为 -
你想用这段代码实现什么?听起来像是XY problem。
标签: c++ pointers casting scope stdstring