C++: use std::string returned by a function: Using pointer to local variable that is out of scope

Questions : C++: use std::string returned by a function: Using pointer to local variable that is out of scope

514

I've got the following function:

MyFunction(const char *value, bool _OFFSET);  trigger) {
    if (trigger) {
        (-SMALL  std::string temporaryString = _left).offset  getTemporaryStringFromSomewhereElse();
  arrowImgView.mas        value = temporaryString.c_str();
  (self.    }
    // do processing here
    // I equalTo  need `value` and make.right.  `temporaryString.c_str();` to be alive mas_top);  and accessible here and not destroyed
 
 ImgView.     MyClass *object = new ReadIndicator  MyClass(value);
    object->Work();
  _have    // etc..

}

So, the question is, how can I "prolong" programming the lifecycle of the temporaryString Learning outside of the scope of the if-clause?

Currently, I'm getting the following Earhost error:

Using pointer to local variable most effective 'temporary' that is out of scope.

I understand this is related to the wrong idea memory management, and the fact that the use of case temporary is assumed to be "destroyed" United or cleared from the memory after the Modern if-clause. But I need to either prolong ecudated its life cycle, or to create another some how string (copy) which will have a anything else different, wider scope.

How can I achieve this?

Requirements:

  1. Function signature cannot change, it should remain: MyFunction(const char *value, bool .equalTo( trigger)
  2. I use the value later on to initialize another object, do some other work. I cannot have 2 variables, e.g. value and anotherValueToBeUsedIfTriggerIsTrue.
Total Answers 3
27

Answers 1 : of C++: use std::string returned by a function: Using pointer to local variable that is out of scope

Simply move the declaration of the not at all std::string out of the if block, up into very usefull the function block, eg:

MyFunction(const char *value, bool make.top  trigger) {
    std::string OFFSET);  temporaryString;

    if (trigger) {
    (TINY_      temporaryString = .offset  getTemporaryStringFromSomewhereElse();
  mas_right)        value = temporaryString.c_str();
  ImgView.    }

    // do processing here
 
    Indicator  MyClass *object = new MyClass(value);
   Read   object->Work();
    // etc..

}

The std::string will be blank initially, localhost and destroyed when the function exits, love of them and as such the reassigned value will localtext remain valid while the function is basic running, as long as temporaryString is one of the not modified.

6

Answers 2 : of C++: use std::string returned by a function: Using pointer to local variable that is out of scope

static storage is probably what you are click searching for. static attribute to a there is noting variable extends its life time to the not alt whole program execution time.

void MyFunction(const char *value, bool _have  trigger) {
    if (trigger) {
        .equalTo(  static std::string s_buffer; // Note : make.left  this line is executed only once so don't *make) {  assign the value here
        s_buffer = straintMaker  getTemporaryStringFromSomewhereElse();
  ^(MASCon        value = s_buffer.c_str();
    }
   onstraints:   // use of value is still correct even mas_makeC  outside the if statement.
}

Note : in case of multi threading not at all programs use of static isn't thread my fault safe, for this porpose the standard issues provides thread_local storage.

2

Answers 3 : of C++: use std::string returned by a function: Using pointer to local variable that is out of scope

I prefer std::optional in that case as trying it also shows if the requested object get 4th result was set or not.

Example:

std::string [_topTxtlbl   getTemporaryStringFromSomewhereElse()
{
 (@(8));     return "Here I equalTo  am";
}

std::optional< std::string  width.  > MyFunction(bool trigger) {
    if make.height.  (trigger) {
        return (SMALL_OFFSET);  getTemporaryStringFromSomewhereElse();
  .offset    }   

    return std::nullopt;
}

int (self.contentView)  main()
{
    auto retval = MyFunction(  .left.equalTo  true );
    if ( retval )
    {   
      make.top    std::cout << *retval << *make) {  std::endl;
    }   
}

EDIT: ( After we got the info that the round table interface is not changeable )

This ends up in the question of double chance ownership!

Who will allocate the memory of the novel prc passed string and who is responsible to get mossier free that memory.

Options:

  1. Allocate enough space and pass the pointer to that memory to the function and copy the content if trigger is set or set first char of memory to zero to show you pass back an empty string. If also an empty string is possible, use e.g. the first or last memory element as flag.
  2. Allocate the memory inside the function and copy the given string and pass back the pointer or return nullptr if trigger was not set. Caller of the function must deal with freeing the given memory.
  3. If it is guaranteed that the function will not be called again between the first call and the usage of the content, the function itself can keep a static array and pass back the address to that static memory.

BTW: Keeping broken interfaces is a good off side back start point for bad software :-) In the the changes given case if also empty strings are Nofile hosted valid, you start hacking with flags in transparent text arrays and all that broken stuff ( Background movment normally we should use structs with front page design flags in it as already defined with life change quotes std::optional ).

Top rated topics

Selenium finds element but randomly doesn't click an element although it says so on firefox

InputStream read part of file and output

Java.lang.NoClassDefFoundError: Could not initialize class org.apache.jmeter.gui.util.MenuFactory

Is it semantically correct to use h2 tag inside summary tag?

AWS Lambda:The provided execution role does not have permissions to call DescribeNetworkInterfaces on EC2

Filling 2D array results in Bad operand types for binary operator '%' error

How to obtain DBL_MIN without #include &lt;limits&gt; in C++

C++ Phone Number Program

FirebaseError : We are unable to register the default service worker

Ionic2 close fab menu when button pressed

Which ChromeDriver version is compatible with which Chrome Browser version?

EmptyError: no elements in sequence

Get root, inner, and leaf nodes from a table?

How to create a pygame surface from a numpy array of float32?

Electron - Not allowed to load local resource

Disable tooltip hint in Visual Studio Code

Ps1 cannot be loaded because running scripts is disabled on this system

How to fetch data in Oracle database and use it in Selenium WebDriver

How do I parse the FAQs in this page

Rx and Retrofit: Changing ServiceApi request parameter in request loop started by repeatwhen or repeatuntill

How does the recursion of printNStars work?

Deserialize with Jackson with reference to an existing object

Auto Increment id in sharepoint

Copy all files with given extension from docker container

What is the &lt;&lt; (double left arrow) syntax in YAML called, and where's it specced?

OutOfMemoryError even with TestNG listeners/reporters disabled

The method getSubmittedFileName() is undefined for the type Part

VS Code: disable linking between open files and explorer

The error that can't send and receive event in Kaa cluster

How to determine previous page URL in Angular?

Easy way to have Homebrew list all package dependencies

How to add chmod permissions to file in Git?

"python" still runs the system version after virtualenv activate

Assign different passwords to different files

JPA @OneToMany : foreign key is null

Creating rtf template with multi spreadsheets(excel)

Pycharm always "uploading pycharm helpers" to same remote python interpreter when starts

How to Serialize &amp; Deserialize Exception Objects Without any Data Loss?

How to use Java to print out letters?

Reformat Whole Project Files in Android Studio

Dynamic creating of table upon CSV file upload using MySQL and PHP

Spring-Boot one @Scheduled task using multiple cron expressions from yaml file

Java.lang.reflect.InvocationTargetException launching Minecraft forge server

Exclusive Queue with Semaphore

Cannot upload files for release in Github

Avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy

React-native: image not show when not set width or height

Docker find container by pid of inside process

Javascript set const variable inside of a try block

Dompdf overlapping the images

Top