此代码是否导致UB
Does this code causes UB?
我检查了gcc和clang,两者都不会生成任何警告。我想临时从foo((的生存期将延长到完整表达式的末尾,也就是bar函数调用中分号的位置。
#include <iostream>
#include <string>
struct A
{
std::string foo() const{ return "aaa"; }
};
void bar(const char* c) {
std::cout << c;
}
int main()
{
A a;
bar(a.foo().c_str()); // Is this safe?
bar(a.foo().substr().c_str()); // or this
}
foo()
(和substr()
(返回的临时将继续存在,直到bar
调用结束(在方法调用链之后(,这是安全的。
int main()
{
A a;
bar(a.foo().c_str());
//temporary is destroyed here
bar(a.foo().substr().c_str());
// and here
}
经典的未定义行为案例:
int main()
{
A a;
const char* charPtr = a.foo().c_str();
printf("%s", charPtr);
}
临时std::string
被创建,指向其缓冲区的指针由c_str()
返回,临时超出范围并被销毁。charPtr
现在是指向无效位置(死std::string
(的指针。
bar(a.foo().c_str());
bar(a.foo().substr().c_str());
简短回答-是的,两者都很安全。
你看到的是一个右值。
右值(历史上称为右值,因为右值可能出现在赋值表达式的右侧(是xvalue、临时对象或其子对象,或与对象无关的值。
阅读更多:什么是rvalues、lvalues、xvalues、glvalues和prvalues?
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 使用 CTRP 时,是否访问访问父构造函数 UB 中的子属性?
- 传递给放置 new 的指针是否是指向其对象表示形式的非 UB 指针?
- 是否通过单元化指针UB访问静态类成员
- 是否可以默认使用UB
- 是否有任何编译器标志可以在下面的代码中用于报告有关 UB 的警告?
- 使用具有不同版本的仅标头库是否会导致 UB
- 移动指针是否经过结构成员 UB?并访问它?
- 是否有任何关于带有UB的代码应该是可访问的保证
- 由于在序列点之间修改变量两次而导致的 UB 是否会转移到"inner"范围?
- 在c++ 11或更高版本中,是否有一种方法可以让constexpr在没有UB的情况下确定endian ?
- 此代码是否导致UB
- 是否将一个无符号整数右移其总位数UB