Передача неконстантной ссылки без именованного объекта?C++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Anonymous
 Передача неконстантной ссылки без именованного объекта?

Сообщение Anonymous »


I have a class StreamRead that represents a file, that I'd like to pass to a constructor for other classes, like a Bitmap for instance. However, I cannot pass an unnamed temporary to Bitmap directly.

Bitmap::Bitmap(StreamRead & in) { // "in" cannot be const because StreamRead's reading operations // change the file position ... } int main() { Bitmap image(StreamRead("filename.png")); // illegal } I've found three ways to address this. The last one is the one I'm using because it's ergonomic, without using mutable, but I worry it may not be well defined in C++:
  • Always making named temporaries when making StreamRead objects
  • Making the file position member in StreamRead mutable and it's reading methods const
  • Giving StreamRead a method that returns a reference to itself, and chaining this call on the constructor.

So my code now looks like this:

StreamRead & StreamRead::pass() { return *this; } int main() { // legal, but is this well-defined? Bitmap image(StreamRead("filename.png").pass()); } Can I depend on pass() always providing a valid reference? Or is the C++ compiler allowed to do funky stuff like destroy the StreamRead object immediately after it gets the reference to it, then call the constructor to Bitmap with the dangling reference?


Источник: https://stackoverflow.com/questions/780 ... med-object
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C++»