C++11 - Distinguishing rvalue pointers

橙三吉。 提交于 2019-12-06 13:05:15

"Hello, World" is not of type const char*. It is of type const char[13] and it is an lvalue, not an rvalue.

When you use "Hello, World" in a context in which it is implicitly converted to a const char* pointing to its initial element, the resulting pointer is an rvalue (because it is a temporary object resulting from an implicit conversion.

For example, in the GCC 4.5.2, a method that returns the type int as opposed to int& is treated as returning int&&.

If you call a function that returns by value (e.g., int), then that function call expression is an rvalue expression. If you call a function that returns an lvalue reference (e.g., int&), then that function call expression is an lvalue expression.

How can I distinguish a variable as a compiler-constructed string?

You can't, really: there's no difference between "Hello, World" and any other const char[13] that you might declare.

As for storing const char*s or any other pointer types in a Standard Library container like std::vector, the container isn't going to touch the pointed-to data: the container is just going to create, move, copy, and destroy the pointers.

If you need to manage the pointed-to data, you need to do that yourself by writing a class to manage the pointed-to object (much like a smart pointer class). The idiom of writing a class to manage a resource like this is called "Resource Acquisition is Initialization" (RAII) or "Scope-Bound Resource Management" (SBRM).

Does this mean that, for any container that holds a const char*, the data should be copied by means other than C++'s move semantics?

It means that the pointer is copied. Nothing more, nothing less. The pointer must be copied for the container to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!