c++ - 传递给函数的临时对象是否被视为 const?

标签 c++ casting constants

我已将参数传递给函数 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 or T2 is a class type and T1 is not reference-related to T2, user-defined conversions are considered using the rules for copy-initialization of an object of type “cv1 T1” 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/

相关文章:

c# - 使用在运行时定义类型的 'is'

angular - RxJS Observable 发出数字; observer.next() 接受字符串; Typescript 如何处理这个问题?

c++ - 为什么 "auto const&"不是只读的?

c++ - 编辑控件替换背景需要选择HBRUSH吗?

c++ - 是否有合并数值范围的有效算法?

c++ - 无法将 uint8_t vector 迭代器转换为 const uint8_t *

使用 decltype 和 constness 的 C++11 尾随返回成员函数

ios - 如何修复错误 : Binary operator '==' cannot be applied to operands of type 'NSExpression.ExpressionType' and '_'

c++ - 宏覆盖类成员

c++ - 为什么我的简单 hello world C++ 应用程序使用 3 个线程?