我已将参数传递给函数 const&,因为我希望能够将“字符串文字”传递给它。不过我想知道是否可以修改引用,如下所示:
void addObjectToDictionary(int* obj, const std::string& name)
{
for (int = 0; i < 10; ++i)
{
if (/*Name already exists in dictionary*/)
name = "object" + std::to_string(rand());
else { /*Add obj to dictionary*/; return; }
}
}
int main()
{
addObjectToDictionary(new int(6), "somename");
)
我想知道丢弃 std::string 引用上的 const 是否未定义。该网站上的另一个答案说:
const_cast is safe only if you're casting a variable that was originally non-const. For example, if you have a function that takes a parameter of a const char *, and you pass in a modifiable char *, it's safe to const_cast that parameter back to a char * and modify it.
但是,我只想知道调用该函数时创建的临时 std::string 对象是否被视为 const。
最佳答案
首先,你可以使用const_cast
无论你什么时候想要。只是如果您尝试修改一个实际上是 const
的对象,在某种程度上编译器无法在编译时捕获,行为是未定义的。使用const_cast
只会增加您这样做的风险。
至于你的问题临时是否是const
就您而言:答案似乎是"is"。关于针对每个 C++ 标准版本的引用初始化措辞,已经有大量缺陷报告,因此我在这里仅讨论 C++17 措辞。标准中的相关规定为[dcl.init.ref]/5.2.2.1:
If
T1
orT2
is a class type andT1
is not reference-related toT2
, user-defined conversions are considered using the rules for copy-initialization of an object of type “cv1T1
” by user-defined conversion (11.6, 16.3.1.4, 16.3.1.5); the program is ill-formed if the corresponding non-reference copy-initialization would be ill-formed. The result of the call to the conversion function, as described for the non-reference copy-initialization, is then used to direct-initialize the reference. For this direct-initialization, user-defined conversions are not considered.
目前还不清楚 std::string
是否有效纯右值是 cv 限定的,但在任何情况下,纯右值都将用于初始化引用,这由 p5.2.1 控制,它要求纯右值继承正在初始化的引用的 cv 限定符。因此很明显,创建的临时对象的类型为 const std::string
.
所以,在:
const std::string& name = "somename";
你会得到一个const
暂时的,但是当你这样做时
std::string&& name = "somename";
你得到一个非 const
暂时的。临时人员的简历资格与引用人员的简历资格相匹配。
关于c++ - 传递给函数的临时对象是否被视为 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60893342/