Pergunta

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

For example, while the rvalue "Hello, World" is of type const char*. const char* in itself does not mean that a pointer can't be changed. A char* const pointer can't be changed, but that's not what's constructed by the compiler.

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? Is there any way to just move compiler-constructed strings and leave all other strings alone?

For example, in the GCC 4.5.2, a method that returns the type int as opposed to int& is treated as returning int&&. I don't know if the actual standard is supposed to be this way, but that's what the GCC does for the time being.

Edit: To clarify, I mean that the actual memory that the pointer points to should be copied. This means that new memory has to be allocated and that the data from the pointer should be copied to the new location.

Foi útil?

Solução

"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).

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top