Reference to flash memory

see the code below:

object.h

class object
{
public:
 object(const String& name);
private:
 const String& _name; 
};

object.cpp

object::object(const String& name) : _name(name)
{
}

main.ino

constexpr char* name1 PROGMEM = "name1";
void setup()
{
object obj1(name1 );
object obj2(F("name2"));
}

question:
in both obj1, obj2 I reference flash variables, in the objects themselves, the reference will reference the flash memory or there will be created an internal copy to work with?

Doesn't the compiler complain?
You promised the constructor would be passed a String reference, but you passed it a PROGMEM pointer.
You don't have a constructor that accepts a flash memory helper type

ok, than how should I create this constructor? I mean what is the modifier ?

I confess, I don't really know because I try not to use Strings.

Sorry.

(Why are you using Strings?)

The String class has a constructor overload to accept '__FlashStringHelper *':

String(const __FlashStringHelper *str);

So a temporary String will be constructed and passed.

Idk, shouldn't I? I mean for simple things like serial inputs or file names... is char* better?

But only for this case
object obj2(F("name2"));
right?

But, this one won't work:

object obj1(name1 );

Because name1 is a 'const char *' type. So compiler will look in RAM for it, not Flash.

This should work:

object obj2(F("name2"));

I wonder if the optimizer does not just throw everything away as the code does nothing -in which case there would be nothing to complain about

..or everything?
Unless you're doing complex manipulations, why bother with Strings at all?

Ok, maby there is a hole in my education, I don't understand the difference between char* and String, and what should I use in "every" case?

It still was PROGMEM, isn't it working as the F() modifier on a String?

yeah sure, it was just an example, the object class is just a template and there is many other functions.

No.

1 Like

There's no short answer, but String is a class (with a lot of baggage) and char* is just a char pointer.

The F() macro is a trick to fool the compiler into treating a PROGMEM pointer as a different datatype.

Thank you all for your help, I just have 2 more questions.

  1. is there a way to store a flash numeric variable (uint8_t - uint64_t)?
  2. is there a general way for functions to accept flash pointers? like __FlashStringHelper which was mentioned by @gfvalvo

Yes, using the PROGMEM modifier (qualifier? Those two confuse me).
The trick comes in the retrieval.

The FlashStringHelper is for strings (curse you, camel-case)

I got that FlashStringHelper helps with strings, but what helps with things that are not strings?

The "progmem_read" functions.
But they don't really "help", merely "facilitate"

If you go to the reference page, I think they're mentioned under "PROGMEM"