Можно ли динамически выделить временную переменную в C ++? - PullRequest
0 голосов
/ 15 февраля 2012

Можно ли динамически выделить временную переменную в C ++?
Я хочу сделать что-то подобное:

#include <iostream>
#include <string>

std::string* foo()
{
  std::string ret("foo");
  return new std::string(ret);
}

int main()
{
  std::string *str = foo();
  std::cout << *str << std::endl;                                                                                                           
  return 0;
}

Этот код работает, но проблема в том, что мне нужно создать другую строку, чтобы вернуть ее в качестве указателя. Есть ли способ поместить мою временную / локальную переменную в мою кучу без воссоздания другого объекта?
Вот иллюстрация того, как я это сделаю:

std::string* foo()
{
  std::string ret("foo");
  return new ret; // This code doesn't work, it is just an illustration
}

Ответы [ 2 ]

3 голосов
/ 15 февраля 2012

Ну, да, это называется умные указатели:

#include <memory>
std::unique_ptr<std::string> foo()
{
    return std::unique_ptr<std::string>("foo");
}

// Use like this:
using namespace std;
auto s = foo();     // unique_ptr<string> instead of auto if you have an old standard.
cout << *s << endl; // the content pointed to by 's' will be destroyed automatically
                    // when you stop using it

Редактировать: без изменения типа возврата:

std::string* foo()
{
    auto s = std::unique_ptr<std::string>("foo");
    // do a lot of stuff that may throw

    return s.release(); // decorellate the string object and the smart pointer, return a pointer
                        // to the string
}
0 голосов
/ 15 февраля 2012

Как насчет этого:

std::string* foo()
{
    std::string * ret = new std::string("foo");
    // do stuff with ret
    return ret;
}
...